Save foreach loop results in a matrix

I am trying to adapt a for loop to use it in parallel as a foreach loop. For the for loop, I create an empty matrix and then populate it with the values ​​generated by the for loop. But this approach does not work in the foreach loop,

results<-matrix(nrow=length(classes),ncol=length(files))
dimnames(results)[[1]]<-classes
dimnames(results)[[2]]<-files

ptime<-system.time({
    foreach(z = 1:length(files),.packages="raster") %dopar% {
      raster <- raster(paste(folder,files[z],sep=""))
      data<-getValues(raster)
      clp <- na.omit(data)
      for(i in 1:length(classes)){
        results[i,z]<-length(clp[clp==classes[i]])/length(clp)
        print(z)
      }
    }
})

My result matrix is ​​still populated na, it is not populated.

z is a raster file, I am a vector of number classes. I want the number of cells in the raster z for each class i, and then divide this by the total number of cells in the raster z to get this as a fraction.

Any tips on how I can save this as a / dataframe matrix in a foreach loop?

Thanks in advance.


Follow this previous question

+4
source share
1

, foreach. , for. . :

library(foreach)
#you need to assign the loop result
res <- foreach(z = 1:5, .combine=c) %do% {
  a <- z
  a #return value for the iterations
}

res
#[1] 1 2 3 4 5


res <- foreach(z = 1:5, .combine=cbind) %:% foreach(i = 10:13, .combine=c) %do% {
  a <- z+i
  a
}
res
#      result.1 result.2 result.3 result.4 result.5
# [1,]       11       12       13       14       15
# [2,]       12       13       14       15       16
# [3,]       13       14       15       16       17
# [4,]       14       15       16       17       18

, . , print . , .

+1

All Articles