我已经编写了一些 C++ 代码来执行此操作,改编自bigmemory Rcpp 库:
rowSums.cpp
// [[Rcpp::depends(BH)]]
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::depends(BH, bigmemory)]]
#include <bigmemory/MatrixAccessor.hpp>
#include <numeric>
// Logic for BigRowSums.
template <typename T>
NumericVector BigRowSums(XPtr<BigMatrix> pMat, MatrixAccessor<T> mat) {
NumericVector rowSums(pMat->nrow(), 0.0);
NumericVector value(1);
for (int jj = 0; jj < pMat->ncol(); jj++) {
for (int ii = 0; ii < pMat->nrow(); ii++) {
value = mat[jj][ii];
if (all(!is_na(value))) {
rowSums[ii] += value[0];
}
}
}
return rowSums;
}
// Dispatch function for BigRowSums
//
// [[Rcpp::export]]
NumericVector BigRowSums(SEXP pBigMat) {
XPtr<BigMatrix> xpMat(pBigMat);
switch(xpMat->matrix_type()) {
case 1:
return BigRowSums(xpMat, MatrixAccessor<char>(*xpMat));
case 2:
return BigRowSums(xpMat, MatrixAccessor<short>(*xpMat));
case 4:
return BigRowSums(xpMat, MatrixAccessor<int>(*xpMat));
case 6:
return BigRowSums(xpMat, MatrixAccessor<float>(*xpMat));
case 8:
return BigRowSums(xpMat, MatrixAccessor<double>(*xpMat));
default:
throw Rcpp::exception("unknown type detected for big.matrix object!");
}
}
在 R 中:
library(bigmemory)
library(Rcpp)
sourceCpp("rowSums.cpp")
m <- as.big.matrix(matrix(1:9, 3))
BigRowSums(m@address)
[1] 12 15 18