Search code examples
rlistmatrixsparse-matrix

convert list of sparse matrix indices to matrix in R


I have this list of strings:

dat <- list(V1=c("1:23","4:12"),V2=c("1:3","2:12","6:3"))

the list elements V1 and V2 are the columns. 1:23 means "the first entry in this column has value 23". All other entries should be zero. The dimension of the matrix is indicated by the highest entry, in this case we have 2 columns (V1 and V2) and the highest row number is a 6, so it would result in a 2x6 matrix like this:

matrix(c(23,3,
     0,12,
     0,0,
     12,0,
     0,0,
     0,3),nrow=6,ncol=2,byrow=T)

how can this convertion be achieved?


Solution

  • You may also try

    library(dplyr)
    library(tidyr)
    library(Matrix)
    
     d1 <- unnest(dat,col) %>% 
               separate(x, into=c('row', 'val'), ':', convert=TRUE)  %>% 
               extract(col, into='col', '\\D+(\\d+)', convert=TRUE)
    
     as.matrix(with(d1, sparseMatrix(row, col, x=val)))
     #     [,1] [,2]
     #[1,]   23    3
     #[2,]    0   12
     #[3,]    0    0
     #[4,]   12    0
     #[5,]    0    0
     #[6,]    0    3