我同意@csgroen 的观点,即并行执行此计算可能是不必要的,因为计算平均值非常快并且设置它需要开销,但这可能取决于您问题的规模。你的矩阵有多大?
可能不并行的最快方法是使用data.table. 我在下面对一些方法进行了基准测试,包括上一个答案(尽管我无法让 dplyr 版本在我的计算机上运行——我认为是因为mat没有列名)。Data.table 平均需要大约 3 毫秒,并且聚合也不远了。
mat <- matrix(seq(1,10000), ncol = 100)
vect_group = rep(1:10, each = 10)
fn1_agg <- function(mat, vg) {
aggregate(c(mat)~rep(vg, ncol(mat)), FUN = mean)
}
fn2_dt <- function(mat, vg){
DT <- data.table::data.table(m = c(mat), v = rep(vg, ncol(mat)))
data.table::setkey(DT, v)
DT[, list(m = mean(m)), by = v]
}
fn3_split <- function(mat, vg) {
splitData <- split(as.data.frame(mat), vect_group)
sapply(splitData, colMeans)
}
microbenchmark::microbenchmark(fn1_agg(mat, vect_group),
fn2_dt(mat, vect_group),
fn3_split(mat, vect_group))
#> Unit: milliseconds
#> expr min lq mean median
#> fn1_agg(mat, vect_group) 5.169709 5.437589 6.122462 6.293567
#> fn2_dt(mat, vect_group) 1.197218 1.291972 3.004166 1.472097
#> fn3_split(mat, vect_group) 15.480264 15.751230 16.998514 16.267098
#> uq max neval cld
#> 6.481626 9.454458 100 b
#> 1.538948 142.368800 100 a
#> 17.060969 60.686907 100 c
由reprex 包(v0.2.1)于 2019 年 2 月 7 日创建