2015-02-23 92 views
-2

假设在R我们有三列。第一个是1:4的替换随机样本。第二个是根据需要重复1:4。第三只是一个索引。结果应该输出一个粘贴的数字组合,其顺序无关紧要并给出一个计数。请注意,n没有填写在sample中,但应该能够为所有n工作。例如,作为中指出:排列和分组在R

c1 <- sample(1:4, n, replace = TRUE) 
c2 <- c(4:1) 
c3 <- 1 

cbind(c1, c2, c3) 

我们希望我们的结果看起来像这样的事情:

11 x0 
12 x1 
13 x2 
14 x3 
22 x4 
23 x5 
24 x6 
33 x7 
34 x8 
44 x9 

显示x[0:9] != 0

谢谢您的帮助!祝你好运!

+0

谢谢Henrik的编辑。 – Jcrist 2015-02-24 00:45:03

回答

0

我相信我们已经解决了我们自己的问题。原始问题涉及的是来源和目的地,而不是数值。所以,我发布了这个答案 - 这是一个轻松切换到数字。希望这有助于未来的人。

library(dplyr) 
library(sqldf) 
x<-data.frame(orig=as.character(sample(LETTERS[1:10], 100, replace=TRUE)), dest=as.character(sample(LETTERS[1:10], 100, replace=TRUE))) 
x$orig<-as.character(x$orig) 
x$dest<-as.character(x$dest) 

x1<-sort(unique(c(x[,1], x[,2]))) 

x_ind<-data.frame(loc=x1, ind=1:length(x1)) 

xx<-sqldf("select a.*, b.ind as orig_ind from x as a left join x_ind as b on a.orig=b.loc") 
xxx<-sqldf("select a.*, b.ind as dest_ind from xx as a left join x_ind as b on a.dest=b.loc") 

comb<-function(orig, dest, orig_ind, dest_ind) 
    { 
    if (orig_ind<=dest_ind) 
    { 
    out<-paste(orig, dest, sep="-") 
    } else 
    { 
    out<-paste(dest, orig, sep="-") 
    } 
    return(out) 
} 

orig_dest<-apply(xxx, 1, function(x) comb(x[1], x[2], x[3], x[4])) 
xxxx<-data.frame(xxx, orig_dest)