Search code examples
rmatrixsubsetsparse-matrix

Subsetting S4 matrix in R


I have a [4 x 5] matrix that I've named T2:

T2 <- new("dgTMatrix",
      i = as.integer(c(1,1,0,3,3)),
      j = as.integer(c(2,2,4,0,0)), x=10*1:5, Dim=4:5)

colnames(T2) <- c("Anthony", "Benjamin", "Clara", "Dexter", "Elise")



abc <- data.frame(c("Anthony", "Benjamin"))
colnames(abc) <- c("Names")

I want to subset it to obtain a [4 x 2] matrix:

T2.s1 <- subset.matrix(T2, colnames(T2) %in% abc$Names)

Does anybody know why this does not work?

Many thanks,

Abigail


Solution

  • It is not a data.frame, so you cannot use subset, and there are no subset methods for sparseMatrix.

    Just subset it like you will do for a matrix:

     T2[,colnames(T2) %in% abc$Names]
    4 x 2 sparse Matrix of class "dgTMatrix"
         Anthony Benjamin
    [1,]       .        .
    [2,]       .        .
    [3,]       .        .
    [4,]      90        .