Parallel Computing + foreach to change cell values of a matrix
Post date: May 26, 2020 11:12:44 PM
# Here we use a small matrix to illustrate the algorithm;
# This approach is much faster than a nested for loop
library(foreach)
library(parallel)
library(doSNOW)
cores = detectCores()
cl <- makeCluster(cores - 2) # leave two CPUs for other tasks
registerDoSNOW(cl)
x <- matrix(1:100,20,5) # a small 20*5 matrix
# keep track of computing time - can be removed
system.time(y <- foreach(i = 1:nrow(x), .combine = rbind) %:%
foreach(j = 1:ncol(x), .combine = cbind) %dopar% {
if(x[i,j] %in% c(1,22,43,64,85)){x[i,j] <- NA}
else {x[i,j] <- x[i,j]}
x[i,j]
})
stopCluster(cl)
rm(cl) # remove the clusters
colnames(y) <- NULL