简体   繁体   English

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

[英]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. 列表元素V1和V2是列。 1:23 means "the first entry in this column has value 23". 1:23表示“此列中的第一个条目具有值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: 矩阵的维数由最高的条目表示,在这种情况下,我们有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)

how can this convertion be achieved? 如何实现这种转换?

Solution: 解:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM