【问题标题】:split list into lists each of length x将列表拆分为长度为 x 的列表
【发布时间】:2020-10-01 13:38:05
【问题描述】:

简单的问题,给定一个列表:

main_list <- list(1:3,
                  4:6,
                  7:9,
                  10:12,
                  13:15)
main_list
# [[1]]
# [1] 1 2 3

# [[2]]
# [1] 4 5 6

# [[3]]
# [1] 7 8 9

# [[4]]
# [1] 10 11 12

# [[5]]
# [1] 13 14 15

我想将列表拆分为多个列表,将原始列表拆分为长度为x 的列表。所以如果我说x = 2,我会得到 3 个长度为 2、2 和剩余 1 的列表:

target <- list(list(1:3,
               4:6),
               list(7:9,
               10:12),
               list(13:15))
target
# [[1]]
# [[1]][[1]]
# [1] 1 2 3

# [[1]][[2]]
# [1] 4 5 6


# [[2]]
# [[2]][[1]]
# [1] 7 8 9

# [[2]][[2]]
# [1] 10 11 12


# [[3]]
# [[3]][[1]]
# [1] 13 14 15

类似:

my_split <- function(listtest, x) {
  split(listtest, c(1:x))
  }
target <- my_split(main_list, 2)

谢谢

【问题讨论】:

    标签: r list split purrr


    【解决方案1】:

    这是gl的选项

    split(main_list, as.integer(gl(length(main_list), 2, length(main_list))))
    

    可以转换成自定义函数

    f1 <- function(lstA, n) {
          l1 < length(lstA)
          split(lstA, as.integer(gl(l1, n, l1)))
      }
    

    【讨论】:

    • 我从未使用过gl。可能永远不会,但知道它的存在很有趣。
    • @IanCampbell 我以前用过它。大多数情况下,它位于%/% 用于拆分的帖子下
    【解决方案2】:

    编辑:不需要条件逻辑。只需将split()c()rep() 一起使用:

    my_split <- function(l, x){
    
      l_length <- length(l)
      l_div <- l_length / x
    
      split(l, c(rep(seq_len(l_div), each = x), rep(ceiling(l_div), l_length %% x)))
    
    }
    
    my_split(main_list, 2)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-26
      • 2013-11-26
      • 2016-07-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多