【发布时间】: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