[R] min of array

Robert rjadenham at gmail.com
Sat Nov 15 02:26:16 CET 2008


I wanted to get the minimum of an array of dimenstion (nr,nc,6), so
the output was of dimension (nr,nc), ie for each row,column the
minimum of 6 numbers.  I thought apply might be the sensible way, but
I also compared it to looping over each row/column.  In this case the
loop method was faster than my apply (which probably means I wasn't
using apply in the best way).  Then I found that pmin was much faster. 
Here is some example code:

nr <- 300
nc <- 300

aa <- array(rnorm(nr*nc*6),c(nr,nr,6))

system.time(aamin1 <- apply(aa,c(1,2),min))

system.time({
    aamin2 <- matrix(0,nr,nc)
    for(i in 1:nr)
          for(j in 1:nc)
                  aamin2[i,j] <- min(aa[i,j,])
})

system.time(aamin3 <-
pmin(aa[,,1],aa[,,2],aa[,,3],aa[,,4],aa[,,5],aa[,,6]))

I have three questions:
1) is there a better way to use apply than the approach I have taken
2) How can I write a function to use pmin on an array as above, but
when I don't know the size of the array? ie
3) My applications are from images, so it would be good for me to know
how to go about writing efficient code that does this sort of
operation on arrays, but using more complex functions than pmin/pmax.
Would the sensible way to go be to write the function in C and call it
that way?  Hopefully an answer to (1) will answer this too.

Thanks
I'm using R-2.5.1 (out of date I know, but I have tried this at work
using 2.8.0 as well), on linux.



More information about the R-help mailing list