R中的排列和分组

时间:2015-02-23 23:10:20

标签: r combinations permutation

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

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

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

1 个答案:

答案 0 :(得分: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)