将稀疏矩阵索引列表转换为 R 中的矩阵

convert list of sparse matrix indices to matrix in R

我有这个字符串列表:

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

列表元素 V1 和 V2 是列。 1:23 表示 "the first entry in this column has value 23"。 所有其他条目应为零。 矩阵的维度由最高条目表示,在这种情况下,我们有 2 列(V1 和 V2),最高行号是 6,因此它会产生一个 2x6 矩阵,如下所示:

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

如何实现这种转换?

解决方案:

dat <- list(V1=c("1:23","4:12"),V2=c("1:3","2:12","6:3"))
y <- inverse.rle(list(values = 1:length(dat),lengths = sapply(dat,length)))

x <-  as.numeric(unlist(sapply(dat,function(y)sapply(strsplit(y,":"),function(x)x[1]))))
val <- as.numeric(unlist(sapply(dat,function(y)sapply(strsplit(y,":"),function(x)x[2]))))

num_row <- max(x)
num_col <- max(y) 
m = matrix(0, nrow = num_row, ncol = num_col)
m[cbind(x,y)] <- val
m

你也可以试试

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