Naive_Natural2511
Naive_Natural2511

Reputation: 717

Equivalent of row() and col() for big.matrix in R

I am using bigmemory package to handle large matrix of size 8000 x 8000.

What is the equivalent of row() and col() for big matrix?

When I tried using the above two functions to access the big.matrix object, I am receiving the following error.

"Error in row(phi) : a matrix-like object is required as argument to 'row'"

Below is my code snippet.

k <- big.matrix(nrow = 8000, ncol = 8000, type = 'double', init = 0)
k <- ifelse(row(k) < col(k), 0, (row(k)-col(k))^5 + 2)

Upvotes: 1

Views: 566

Answers (1)

F. Priv&#233;
F. Priv&#233;

Reputation: 11728

So, with Rcpp, you can do:

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

// [[Rcpp::export]]
void fillBM(SEXP pBigMat) {

  XPtr<BigMatrix> xpMat(pBigMat);
  MatrixAccessor<double> macc(*xpMat);

  int n = macc.nrow();
  int m = macc.ncol();

  for (int j = 0; j < m; j++) {
    for (int i = j; i < n; i++) {
      macc[j][i] = pow(i - j, 5) + 2;
    }
  }
}

/*** R
library(bigmemory)
k <- big.matrix(nrow = 8000, ncol = 8000, type = 'double', init = 0)
k.mat <- k[]

system.time(
  fillBM(k@address)
)
k[1:5, 1:5]

system.time(
  k.mat <- ifelse(row(k.mat) < col(k.mat), 0, (row(k.mat)-col(k.mat))^5 + 2)
)
k.mat[1:5, 1:5]
all.equal(k.mat, k[])
*/

The Rcpp function takes 2 sec while the R version (on a standard R matrix) takes 10 seconds (and much more memory).

Upvotes: 1

Related Questions