【发布时间】:2019-07-29 22:01:11
【问题描述】:
我有 34 个栅格(nrow:17735,ncol:11328,ncell:200902080),值为 0 和 1,每个 4Mb。我想要这些值的累积和零重置。
我尝试了几种基于:Cumulative sum that resets when 0 is encountered
library(microbenchmark)
library(compiler)
library(dplyr)
library(data.table)
x <- c(0,0,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0)
fun = function(x)
{ cs = cumsum(x)
cs - cummax((x == 0) * cs)
}
funC <- cmpfun(fun)
microbenchmark(
funcioEx = fun(x),
funComEx = funC(x),
lapplyEx = unname(unlist(lapply(split(x,cumsum(c(0,diff(x) != 0))), cumsum))),
dataTaEx = data.table(x)[, whatiwant := cumsum(x), by = rleid(x==0L)],
reduceEx = Reduce(function(x, y) if (y == 0) 0 else x+y, x, accumulate=TRUE)
)
我想针对我的数据优化此过程,因为使用第二个选项(funComEx,最快)大约需要 3 个小时。
【问题讨论】:
-
我认为
fun可能是 R 中最快的方法之一。查看Rcpp包以获得更快的速度可能会有所帮助。
标签: r optimization cumsum microbenchmark