【问题标题】:Adding elements of combinations of vector in a list in R在R中的列表中添加向量组合的元素
【发布时间】:2021-11-26 02:39:54
【问题描述】:

我是 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

但是当我创建一个列表梳

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()

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

【问题讨论】:

    标签: r list loops combinatorics


    【解决方案1】:

    这似乎给了你想要的

    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() 函数中才能将其附加为一个。

    【讨论】:

      【解决方案2】:

      我们可以像下面这样使用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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-05-17
        • 1970-01-01
        • 2017-12-07
        • 2019-02-23
        • 1970-01-01
        • 1970-01-01
        • 2011-02-16
        相关资源
        最近更新 更多