rbigdatadiagonalr-bigmemory

Calculate the diagonal of a big.matrix in R


I am working with several big squared matrices of 1.3e6 rows, and I want to the diagonal of all of them. I need an efficient way to do it, but I can not use diag()

library(bigmemory)
A=big.matrix(nrow=1.3e6,ncol=1.3e6,init=3)
diag(A)

Any idea? Thank you very much for your time


Solution

  • Ok, in fact, you don't need Rcpp here. Just use the special matrix accessor of two-columns:

    library(bigmemory)
    
    X <- big.matrix(10, 10); X[] <- 1:100
    
    d <- min(dim(X))
    X[cbind(1:d, 1:d)]
    

    X[cbind(1:d, 1:d)] will access X[1, 1], X[2, 2], ..., X[d, d].