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 then fill it with the values generated by the for loop. But this approach doesn't 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 results matrix is still just filled with na's, it doesn't get populated.
z is a raster file, i is a vector of numerical classes. I want the number of cells in raster z for each class i, and then divide this by the total number of cells in raster z to get this as a proportion.
Any advice on how I can save this as a matrix/dataframe in a foreach loop?
Thank you in advance.
Follow up of this previous question