[R] saving multiple arrays from a foreach loop

Nicolas Berkowitsch nicolas.berkowitsch at unibas.ch
Fri May 27 09:14:47 CEST 2011


Dear R-List member,

I have a problem when I'm trying to save two arrays from a foreach-loop. 
I'm also not sure whether this is possible or just my inexperience. 
However, this works perferctly fine with a for-loop.

Here is an example code - any help is much appreciated!!:

############
n.vpn = 2
n.run= 3

# create to empty matrices
sme = matrix(NA,4,n.vpn)
test = matrix(NA,4,n.vpn)
# arrays to save the data from a nested (for) loop
x = array(NA,dim=c(4,n.vpn,n.run))
y = array(NA,dim=c(4,n.vpn,n.run))

# function which returns two matrices saved in one list
check <-function(n) {
     for(i in 1:n.vpn) {
         sme[,i] = c((1+i):(4+i))
         test[,i]= c((5+i):(8+i))
     }
     retval = list(sme=sme,test=test)
     return(retval)
}

# Call the check function multiple time and save every list entry into a 
specific arrays "x" and "y"; stop time
  system.time(for(j in 1:n.run) {
      z = check(j)
      x[,, j] <- z$sme
      y[,, j] <- z$test
      })

#### trying to do the same with a foreach loop - does not work!!

require(doSMP)
workers <- startWorkers(2) # My computer has 2 cores
registerDoSMP(workers)

notcreative = array(NA,dim=c(4,n.vpn,n.läufe))
tempList = list(matrix(NA,4,n.vpn),matrix(NA,4,n.vpn))
  system.time(notcreative <- foreach(j=1:n.run) %dopar% {
      tempList=check(j)
      x[,,j] = tempList$sme
      y[,,j] = tempList$test
      })
stopWorkers(workers)

-- 
____________


lic. phil. Nicolas A. J. Berkowitsch
Universität Basel
Fakultät für Psychologie
Economic Psychology
Missionsstrasse 62a
CH-4055 Basel

Tel.     +41 61 267 05 75
E-Mail   nicolas.berkowitsch at unibas.ch
Web      http://psycho.unibas.ch/abteilungen/abteilung-details/home/abteilung/economic-psychology/



More information about the R-help mailing list