Skip to content

Improve a browse through list items - Transform a loop to apply-able function.

5 messages · Jean V Adams, Klint Gore, Patrizio Frederic +1 more

1 day later
#
How about something along the line of 

library(foreach)
library(doMC)
registerDoMC()   

# larger matrix for timing test
a <- b <- c <- d <- result <- matrix(nrow=1000, ncol=1000)
a[] <- sample.int(n=100,size=1000000,replace=TRUE)
b[] <- sample.int(n=100,size=1000000,replace=TRUE)
c[] <- sample.int(n=100,size=1000000,replace=TRUE)
d[] <- sample.int(n=100,size=1000000,replace=TRUE)
result[] <- NA
mylist <- list(a,b,c,d)
nrows=nrow(a)
ncols=ncol(a)

system.time(
{
  result<-foreach (row=1:nrows, .combine=rbind) %dopar%
  {
    thisrow=vector()

    for (col in 1:ncols)
    {
      tmpList <- log(mylist[[1]][row, col])
      for (listitem in 2:length(mylist))
      {
        tmpList <- c(tmpList, log(mylist[[listitem]][row, col]))
      }
      thisrow <- cbind(thisrow,sd(tmpList))
    }
    thisrow
  }
}
)

Example as written with the larger matrix
   user  system elapsed 
 62.660   0.000  62.722

%do%
   user  system elapsed 
 66.910   0.020  66.979 

%dopar%
   user  system elapsed 
 71.390   4.840   3.402


Klint.
#
Hi robin,
I'm not sure is what you need, but that's an esthetically nice
solution (one single line without any loop :) )

matrix(apply(log(cbind(as.numeric(a),as.numeric(b),as.numeric(c),as.numeric(d))),1,sd),3)

hope it could help,

PF
On Mon, Dec 12, 2011 at 5:15 PM, Robin Cura <robin.cura at gmail.com> wrote:

  
    
1 day later