[R] How to make the "apply" faster

Charles C. Berry ccberry at ucsd.edu
Sat Jul 9 23:46:23 CEST 2016


On Sat, 9 Jul 2016, Debasish Pai Mazumder wrote:

> I have 4-dimension array x(lat,lon,time,var)
>
> I am using "apply" to calculate over time
> new = apply(x,c(1,2,4),FUN=function(y) {length(which(y>=70))})
>
> This is very slow. Is there anyway make it faster?

If dim(x)[3] << prod(dim(x)[-3]),

new <-  Reduce("+",lapply(1:dim(x)[3],function(z) x[,,z,]>=70))

will be faster.

However, if you can follow Peter Langfelder's suggestion to use rowSums, 
that would be best. Even using rowSums(aperm(x,c(1,2,4,3)>=70,dims=3) and 
paying the price of aperm() might be better.

Chuck



More information about the R-help mailing list