在R中没有重复的组合

时间:2014-01-24 17:53:48

标签: r variables combinations paste

我试图获得变量元素长度3的所有可能组合。虽然它部分适用于combn(),但我并没有得到我想要的输出。这是我的例子

x <- c("a","b","c","d","e")
t(combn(c(x,x), 3)) 

我得到的输出看起来像这样

       [,1] [,2] [,3]
  [1,] "a"  "b"  "c" 
  [2,] "a"  "b"  "d" 
  [3,] "a"  "b"  "e" 

由于两个原因,我对这个命令并不满意。我想得到一个输出“a + b + c”“a + b + b”....不幸的是我无法用paste()或其他东西编辑输出。

我也期待着每组字母的一个组合,即我得到“a + b + c”或“b + a + c”但不是两者。

2 个答案:

答案 0 :(得分:5)

尝试类似:

x <- c("a","b","c","d","e")
d1 <- combn(x,3) # All combinations

d1 

#     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,] "a"  "a"  "a"  "a"  "a"  "a"  "b"  "b"  "b"  "c"  
# [2,] "b"  "b"  "b"  "c"  "c"  "d"  "c"  "c"  "d"  "d"  
# [3,] "c"  "d"  "e"  "d"  "e"  "e"  "d"  "e"  "e"  "e"

nrow(unique(t(d1))) == nrow(t(d1))
# [1] TRUE

d2 <- expand.grid(x,x,x) # All permutations 

d2

#     Var1 Var2 Var3
# 1      a    a    a
# 2      b    a    a
# 3      c    a    a
# 4      d    a    a
# 5      e    a    a
# 6      a    b    a
# 7      b    b    a
# 8      c    b    a
# 9      d    b    a
# ...

nrow(unique(d2)) == nrow(d2)
# [1] TRUE

答案 1 :(得分:2)

尝试

x <- c("a","b","c","d","e")
expand.grid(rep(list(x), 3))