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
Karen source
share