我有以下字符串列表:
dat <- list(V1=c("1:23","4:12"),V2=c("1:3","2:12","6:3"))
列表元素V1和V2是列。1:23表示“此列中的第一个条目的值为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)
如何实现这种转换?
您也可以尝试
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句