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

无序组合并将结果存储在r中的矩阵中,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` 我不知道怎么做。谢谢你的帮助 这个想法来自于这个问题下的评论部分: 我的改编不是很优雅。。。但它似乎起到了作用 output <- expand.grid(rep(list(c('a', 'b', 'c')), 3

假设我有一个列表(
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`

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

这个想法来自于这个问题下的评论部分:

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

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

输出想法取自此问题下的评论部分:

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

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

output要准确执行所需操作,请在
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,]

要完全执行您想要的操作,请在
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,]

可能的答案:使用
expand.grid(列表(a,b,c))
@YOLO谢谢!这正是我要找的。@YOLO实际上不是。但还是要谢谢你。@vincent-实际上是这样,只要去掉第一行-例如
expand.grid(0:1,0:1,0:1)[-1,]
可能的答案:使用
expand.grid(list(a,b,c))
@YOLO谢谢!这正是我要找的。@YOLO实际上不是。但还是要谢谢你。@vincent-实际上是这样,只需删除第一行即可-例如
expand.grid(0:1,0:1,0:1)[-1,]