r - R中几个big.matrix对象的元素平均值
问题描述
我有 17 个 filebacked 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
推荐阅读
- javascript - 带有输入文本的单选按钮
- javascript - XMLHttpRequest.send(data) 不向 Django 视图函数传递数据
- linux - Linux MS Teams 预览版 + XMonad:可能会有通知浮动吗?
- reactjs - 选择并按住并拖动形状应水平或垂直滚动
- python - python:如何添加一个搜索路径
- python - 如何使用 Django 中的列表创建正确的 get 查询集以获取值
- javascript - 如何使用 For 循环动态更改 Vue Js 中的变量?
- discord - 分片状态命令 - Discord.JS V12
- python-3.x - 如何使用 pip 将 python 包下载到具有公共访问权限的 Google Cloud Storage 存储桶中并从那里安装
- python - 根据此数据框中其他列中的特定值更改熊猫数据框中的一列中的值(使用应用),并带有掩码