Home > Back-end >  Coerce R matrix to dgTMatrix inside a function
Coerce R matrix to dgTMatrix inside a function

Time:05-07

Given a matrix object in R, it's easy to coerce it to a sparse matrix in triplet format:

library(Matrix)
m <- matrix(rbinom(100,1,0.5),10,10)
m <- as(1*m, "dgTMatrix")

But, what is the correct way to do this inside an R function (i.e., without attaching the Matrix library)? I know that m <- Matrix::as(1*m, "dgTMatrix") is not correct, but suspect it will be something along those lines.

CodePudding user response:

Typically you would do something like

if (requireNamespace("Matrix", quietly = TRUE))
    m <- as(m, "dgTMatrix")
else
    stop("package ", sQuote("Matrix"), " not found on library path")

to load the package as necessary, without attaching it. This has the effect of registering coercion (and other) methods without making all of the objects exported by Matrix available to the user.

If your function is part of an R package with Matrix listed in Imports, then you could do

m <- as(m, "dgTMatrix")

directly, without requireNamespace. If Matrix is instead listed in Suggests, then you would need to use requireNamespace as above. In both cases, you would want Imports to include package methods and NAMESPACE to contain the directive importFrom(methods, as).

Tangentially, note that that your 1*m, effectively coercing m from integer to double, is unnecessary. The coercion method does that work for you:

selectMethod("coerce", c("matrix", "dgTMatrix"))
Method Definition:

function (from, to = "dgTMatrix", strict = TRUE) 
{
    x <- as.double(from)
    nz <- isN0(x)
    new("dgTMatrix", Dim = dim(from), Dimnames = .M.DN(from), 
        i = row(from)[nz] - 1L, j = col(from)[nz] - 1L, x = x[nz])
}
<bytecode: 0x1079ded68>
<environment: namespace:Matrix>

Signatures:
        from     to         
target  "matrix" "dgTMatrix"
defined "matrix" "dgTMatrix"

CodePudding user response:

For use in a function that will be part of an R package, I think this should work:

m <- matrix(rbinom(100,1,0.5),10,10)
m_ <- Matrix::spMatrix(nrow(m), 
                       ncol(m), 
                       i = which(m != 0, arr.ind = T)[,1], 
                       j = which(m != 0, arr.ind = T)[,2], 
                       x = rep(1,sum(m)))
  • Related