在 R 的列表中添加向量组合的元素

Adding elements of combinations of vector in a list in R

我是 R 的新手,所以我想做的是给我一个正整数向量,比如

index <- 1:3

我想用这个向量找到所有可能的数字组合而不重复,我是这样实现的

for (i in 1:length(index)) {
 combn(index,i)
 j = 1
 while (j <= nrow(t(combn(index,i)))) {
     print(t(combn(index,i))[j,])
     j = j + 1
     append(comb, j)
 }
 }

这给我的输出为

[1] 1
[1] 2
[1] 3
[1] 1 2
[1] 1 3
[1] 2 3
[1] 1 2 3

但是当我创建一个列表 comb <- list() 并尝试如下附加每个输出时:

for (i in 1:length(index)) {
combn(index,i)
j = 1
while (j <= nrow(t(combn(index,i)))) {
    append(comb, t(combn(index,i))[j,])
    j = j + 1
}
}

问题是当我调用

时它给出了我的空列表
comb
list()

我希望创建一个包含这些元素的列表,并使用它们从数据框中检索那些索引行。你知道我怎样才能做到这一点吗?欢迎任何帮助。谢谢!

这似乎给了你想要的

index <- 1:3

comb <- list()

for (i in 1:length(index)) {
  combn(index,i)
  j = 1
  while (j <= nrow(t(combn(index,i)))) {
    comb <- c(comb, list(t(combn(index,i))[j,]))
    j = j + 1
  }
}

comb

输出

[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] 1 2

[[5]]
[1] 1 3

[[6]]
[1] 2 3

[[7]]
[1] 1 2 3

请注意,您必须将附加列表分配回来。此外,如果您附加一个带有矢量的列表,每个矢量元素将成为新列表中的一个单独元素。您必须将该向量包装在 list() 函数中才能将其作为一个附加。

我们可以像下面这样使用 unlist + lapply

unlist(
  lapply(
    seq_along(index),
    combn,
    x = index,
    simplify = FALSE
  ),
  recursive = FALSE
)

这给出了

[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] 1 2

[[5]]
[1] 1 3

[[6]]
[1] 2 3

[[7]]
[1] 1 2 3