【问题标题】:How to split list at every 10th item in R?如何在R中的每10个项目拆分列表?
【发布时间】:2016-11-06 17:34:33
【问题描述】:

我有一个包含 100 个项目的列表。 我想在代码 1 中的每 10 项之后拆分它。 代码 2 是关于两个前列表的列表,并将其拆分为 20 个列表,每个列表 10 项。

代码 1

预期输出:10 个包含 10 个项目的列表。

A <- 100
a <- rnorm(A) # [1:100]
n <- 10
str(a)

# Not resulting in equal size of chunks with vectors so reject
# http://stackoverflow.com/a/3321659/54964
#d <- split(d, ceiling(seq_along(d)/(length(d)/n)))

# Works for vectors but not with lists
# http://stackoverflow.com/a/16275428/54964
#d <- function(d,n) split(d, cut(seq_along(d), n, labels = FALSE)) 

str(d)

测试代码2

输入:两个列表的列表

aa <- list(a, rnorm(a))

预期输出:20 个 10 项大小的列表

测试 Loki 的答案

segmentLists <- function(A, segmentSize) {
  res <- lapply(A, function(x) split(unlist(x), cut(seq_along(unlist(x)), segmentSize, labels = F)))

  #print(res)    
  res <- unlist(res, recursive = F)
}

segmentLists(aa, 10)

输出:循环继续,永不停止

操作系统:Debian 8.5
R:3.3.1

【问题讨论】:

  • “分成 10 个项目的块” 是一个常用术语。标记chunks

标签: r list split chunks


【解决方案1】:

您可以使用lapply

aa <- list(a, rnorm(a))
aa
n <- 10

x <- lapply(aa, function(x) split(unlist(x), cut(seq_along(unlist(x)), n, labels = F)))
y <- unlist(x, recursive = F)
str(y)
# List of 20
# $ 1 : num [1:10] 1.0895 -0.0477 0.225 -0.6308 -0.1558 ...
# $ 2 : num [1:10] -0.469 -0.381 0.709 -0.798 1.183 ...
# $ 3 : num [1:10] 0.757 -1.128 -1.394 -0.712 0.494 ...
# $ 4 : num [1:10] 1.135 0.324 0.75 -0.83 0.794 ...
# $ 5 : num [1:10] -0.786 -0.068 -0.179 0.354 -0.597 ...
# $ 6 : num [1:10] -0.115 0.164 -0.365 -1.827 -2.036 ...
...

length(y)
# [1] 20

要删除 y 中的列表元素的名称($ 1$ 2 等),您可以使用 unname()

str(unname(y))
# List of 20
# $ : num [1:10] 1.0895 -0.0477 0.225 -0.6308 -0.1558 ...
# $ : num [1:10] -0.469 -0.381 0.709 -0.798 1.183 ...
# $ : num [1:10] 0.757 -1.128 -1.394 -0.712 0.494 ...
# $ : num [1:10] 1.135 0.324 0.75 -0.83 0.794 ...
# $ : num [1:10] -0.786 -0.068 -0.179 0.354 -0.597 ...
...

使用函数,您必须在函数末尾返回res

segmentLists <- function(A, segmentSize)
{
  res <- lapply(A, function(x) split(unlist(x), cut(seq_along(unlist(x)), segmentSize, labels = F)))

  #print(res)

  res <- unlist(res, recursive = F)
  res <- unname(res)
  res
}

【讨论】:

  • @DavidArenburg,没错。我改变了它。 @Masi:我添加了解决问题的unlist(...)。查看length(...)的结果。
  • 这些是列表元素的名称。请参阅编辑如何删除它们。
  • 函数不循环,但你不返回任何对象。您必须在函数末尾返回结果res。查看编辑
  • 我认为没有列表矩阵,我错了吗?但是,您可以尝试将矩阵矢量化为包含 4 个列表的列表。然后,就可以应用该功能了。
  • 我认为这将超出您的问题的答案,该问题已得到回答。我想This post 回答了这个问题。
猜你喜欢
  • 2014-03-21
  • 1970-01-01
  • 2016-08-02
  • 2012-09-30
  • 2017-05-20
  • 2014-06-08
  • 1970-01-01
  • 1970-01-01
  • 2014-04-05
相关资源
最近更新 更多