代码之家  ›  专栏  ›  技术社区  ›  Theskywalker15

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

  •  0
  • Theskywalker15  · 技术社区  · 4 年前

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

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

    0 回复  |  直到 4 年前
        1
  •  2
  •   ThomasIsCoding    4 年前

    我们可以使用 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
    
        2
  •  1
  •   Dharman vijay    4 年前

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