我的问题与这个问题密切相关:
Split a vector into chunks in R
我试图将一个大向量分成已知的块大小,但速度很慢。具有偶数余数的向量的解决方案在这里:
存在因素时的快速解决方案如下:
Split dataframe into equal parts based on length of the dataframe
我想处理没有(大)因素存在的情况,因为我想要相当大的块。
我的矢量示例比我现实生活中的矢量小得多:
d <- 1:6510321
# Sloooow
chunks <- split(d, ceiling(seq_along(d)/2000))
最佳答案
使用 llply
来自 plyr
包我能够减少时间。
chunks <- function(d, n){
chunks <- split(d, ceiling(seq_along(d)/n))
names(chunks) <- NULL
return(chunks)
}
require(plyr)
plyrChunks <- function(d, n){
is <- seq(from = 1, to = length(d), by = ceiling(n))
if(tail(is, 1) != length(d)) {
is <- c(is, length(d))
}
chunks <- llply(head(seq_along(is), -1),
function(i){
start <- is[i];
end <- is[i+1]-1;
d[start:end]})
lc <- length(chunks)
td <- tail(d, 1)
chunks[[lc]] <- c(chunks[[lc]], td)
return(chunks)
}
# testing
d <- 1:6510321
n <- 2000
system.time(chks <- chunks(d,n))
# user system elapsed
# 5.472 0.000 5.472
system.time(plyrChks <- plyrChunks(d, n))
# user system elapsed
# 0.068 0.000 0.065
identical(chks, plyrChks)
# TRUE
您可以使用
.parallel
提高速度来自 llpyr
的参数功能。或者您可以使用 .progress
添加进度条范围。
关于r - 在 R 中快速将大向量分割成 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31062486/