无序组合,并将结果存储在r中的矩阵中

  • 本文关键字:存储 组合 结果 无序 r
  • 更新时间 :
  • 英文 :


假设我有一个列表(a, b, c(,我想找出它们的所有可能组合,并存储在矩阵中,如:

a b c
[1,] 1 0 0
[2,] 0 1 0
[3,] 0 0 1
[4,] 1 1 0
[5,] 1 0 1
[6,] 0 1 1
[7,] 1 1 1`

我不知道怎么做。谢谢你的帮助!

要执行您想要的操作,请在gtools包中使用permutations。其工作原理如下:

m <- permutations(2, 3, v=c(0,1), repeats.allowed=T)
colnames(m) <- c('a','b','c')
# delete [0,0,0]
m <- m[-1,]

收益率:

a b c
[1,] 0 0 1
[2,] 0 1 0
[3,] 0 1 1
[4,] 1 0 0
[5,] 1 0 1
[6,] 1 1 0
[7,] 1 1 1 

想法取自此问题下的评论部分:使用3个字母生成长度为2的所有组合

我的改编不是很优雅。。。但它似乎起到了作用。

output <- expand.grid(rep(list(c('a', 'b', 'c')), 3))
colnames(output) <- c('a', 'b', 'c')
for (col in colnames(output)) { 
output[, col] <- as.character(output[,col])
output[, col] <- ifelse(output[, col]==col, 1, 0)
}
output <- output[!duplicated(output), ]
rownames(output) <- NULL
print(output)
# a b c
# 1 1 0 0
# 2 0 0 0
# 3 1 1 0
# 4 0 1 0
# 5 1 0 1
# 6 0 0 1
# 7 1 1 1
# 8 0 1 1

最新更新