你可以运行
apply
在多个集群上并行运行
firstMat<-matrix(c(T,F,T,F,F,T,T,F,F,F),nrow=5,ncol=2)
secondMat<-matrix(c(1,0,0,0,1,0,0,0,1,1,1,0,1,0,1,1,1,0,0,0,1,1,1,0,1),nrow=5,ncol=5)
# create custers
library(doSNOW)
cl <- makeCluster(2, type = "SOCK") # creates 2 clusters
# can use detectCores() from package parallel to check number of cores in your machine
registerDoSNOW(cl)
clusterExport(cl,list("secondMat")) # need to export secndMAT to each cluster since will be used in cluster
# Option 1: Using parApply from package `parallel`
library(parallel)
parApply(cl,firstMat,2,function(x) sum(secondMat[x,x]))
# Option 2: Using aaply from package `plyr`
library(plyr)
aaply(firstMat,2,function(x) sum(secondMat[x,x]),.parallel=T)
stopCluster(cl)
在这个小的可复制示例中,它没有显示任何速度改进,但我希望这两个选项都比
申请
对于大型矩阵