本文介绍了可以并行使用pbapply吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这段代码想要对矩阵的列求和.
I have this code where I want to sum the columns of a matrix.
我还希望具有几个功能(我的矩阵比下面的示例大得多):
I also want to have a couple of features (my matrix is much bigger than the example below):
- 使用多个内核
- 具有进度栏
我尝试了pbapply包中的pbapply
,但是没有运气.我的代码是:
I tried pbapply
from the pbapply package but without luck. My code is:
library(pbapply)
library(parallel)
mat <- matrix(ncol=20, nrow = 50, data = runif(1000))
# sum of the columns
matsum <- apply(mat,2,sum)
# now the same in parallel
cl <- makeCluster(2)
pboptions(type = "txt")
parmat <- pbapply(mat,2,sum, cl=cl)
stopCluster(cl)
这会导致错误:
我的问题是,根本可以并行运行pbapply吗?
My question is, is it possible at all to run pbapply in parallel?
推荐答案
pbapply
不采用cl
自变量,因此否.但是,您可以将矩阵转换为data.frame(如果可行),并使用适用于列的sapply.
pbapply
doesn't take the cl
argument, so no. You can, however, convert your matrix to a data.frame (if that's feasible), and use sapply which should work on columns.
mat <- as.data.frame(mat)
parmat <- pbsapply(X = mat, FUN = sum, cl = cl)
或者,您可以尝试
colSums(mat)
这是主力军.
这篇关于可以并行使用pbapply吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!