r - R 中几个 big.matrix 对象的逐元素平均值

标签 r bigdata r-bigmemory

我有 17 个文件支持的 big.matrix 对象(dim 10985 x 52598,每个 4.3GB),我想计算其中的逐元素平均值。结果可以存储在另一个 big.matrix (gcm.res.outputM) 中。

biganalytics::apply() 不起作用,因为 MARGIN 只能设置为 1 或 2。我尝试使用 2 个 for 循环,如此处所示

gcm.res.outputM <- filebacked.big.matrix(10958, 52598, separated = FALSE, backingfile = "gcm.res.outputM.bin", backingpath = NULL, descriptorfile = "gcm.res.outputM.desc", binarydescriptor = FALSE)

for(i in 1:10958){
   for(j in 1:52598){
    t <- rbind(gcm.res.output1[i,j], gcm.res.output2[i,j],gcm.res.output3[i,j], gcm.res.output4[i,j],
           gcm.res.output5[i,j], gcm.res.output6[i,j],gcm.res.output7[i,j], gcm.res.output8[i,j],
           gcm.res.output9[i,j], gcm.res.output10[i,j],gcm.res.output11[i,j], gcm.res.output12[i,j],
           gcm.res.output13[i,j], gcm.res.output14[i,j],gcm.res.output15[i,j], gcm.res.output16[i,j],
           gcm.res.output17[i,j])
    tM <- apply(t, 2, mean, na.rm = TRUE)
    gcm.res.outputM[i,j] <- tM
    }
}

每行 i 大约需要 1.5 分钟,因此大约需要运行 11 天。

有没有人对如何加速这个计算有任何想法?我使用的是具有 16GB RAM 的 64x Windows10 机器。

谢谢!

最佳答案

您可以使用此 Rcpp 代码:

// [[Rcpp::depends(BH, bigmemory, RcppEigen)]]
#include <bigmemory/MatrixAccessor.hpp>
#include <RcppEigen.h>
using namespace Eigen;
using namespace Rcpp;

// [[Rcpp::export]]
void add_to(XPtr<BigMatrix> xptr_from, XPtr<BigMatrix> xptr_to) {

  Map<MatrixXd> bm_from((double *)xptr_from->matrix(),
                        xptr_from->nrow(), xptr_from->ncol());
  Map<MatrixXd> bm_to((double *)xptr_to->matrix(),
                      xptr_to->nrow(), xptr_to->ncol());

  bm_to += bm_from;
}

// [[Rcpp::export]]
void div_by(XPtr<BigMatrix> xptr, double val) {

  Map<MatrixXd> bm((double *)xptr->matrix(),
                   xptr->nrow(), xptr->ncol());

  bm /= val;
}

然后如果你有一个相同大小的 big.matrix 对象列表,你可以这样做:

library(bigmemory)
bm_list <- lapply(1:5, function(i) big.matrix(1000, 500, init = i))
res <- deepcopy(bm_list[[1]])
lapply(bm_list[-1], function(bm) add_to(bm@address, res@address))
res[1:5, 1:5]  # verif
div_by(res@address, length(bm_list))
res[1:5, 1:5]  # verif

关于r - R 中几个 big.matrix 对象的逐元素平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52048515/

相关文章:

r - 使用 count()、aggregate()、data.table() 或 dplyr() 汇总数据(均值、标准差)

r - 计算汇总统计数据,然后将所有结果合并到单个 data.frame 中

java - 从 Spark Java API 中的参数类型创建 DataType

r - 使用 big.matrix 对象计算欧几里得距离矩阵

R: big.matrix 乘法

r - 如何通过%>%运算符(dplyr)使用逻辑函数

r - 识别 R 中六个变量的所有组合

apache-spark - SQL查询转Spark Dataframe结构化数据处理

hadoop - 将oozie作业输出发送到邮件ID