newbie
newbie

Reputation: 767

plyr::aaply is very slow compared to nested loops

I have a simple task to do. I have a 3D array (10,1350,1280) and I want to calculate the min over the first dimensions. I can do it using aaply like the following

minObs <- plyr::aaply(obs, c(2,3), min)  # min of observation

But it is extremely slow compared to when I just write a nested loop.

minObs<-matrix(nrow=dim(obs)[2],ncol=dim(obs)[3])

for (i in 1:dim(obs)[2]){
  for (j in 1:dim(obs)[3]){
    minObs[i,j]<-min(obs[,i,j],na.rm = TRUE)
  }
}

I am new to R , but I am guessing that I am doing something wrong with aaply function. And hint would be very much appreciated. How can I speed up using aaply?

Upvotes: 2

Views: 161

Answers (1)

thelatemail
thelatemail

Reputation: 93908

Why not just use the base apply function?

apply(obs, c(2,3), min)

It's fast, doesn't require loading an additional package and gives the same result, as per:

all.equal(
  apply(obs, 2:3, min), 
  aaply(obs, 2:3, min), check.attributes=FALSE) 
#[1] TRUE

Timings using system.time() using a 10 x 1350 x 1280 array:

Loop
#   user  system elapsed 
#   3.79    0.00    3.79 

Base apply()
#   user  system elapsed 
#   2.87    0.02    2.89 

plyr::aaply()
#Timing stopped at: 122.1 0.04 122.24

Upvotes: 1

Related Questions