【问题标题】:convert list of sparse matrix indices to matrix in R将稀疏矩阵索引列表转换为R中的矩阵
【发布时间】:2015-07-24 18:52:58
【问题描述】:

我有这个字符串列表:

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)

如何实现这种转换?

【问题讨论】:

  • 您的意思是写matrix(c(23,3, 吗?
  • “所有其他条目为零”是错误的,或者充其量是令人困惑的......
  • @EricBrooks 谢谢,已更正。

标签: r list matrix sparse-matrix


【解决方案1】:

你也可以试试

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

【讨论】:

  • unnest(setNames(dat, seq_along(dat)),col)stack(dat) 非常相似。 as.numeric 在后者中的 ind 上的效果与在前者中的 col 上一样好。
  • @Frank 首先,我使用了stack(在编辑中),但后来认为人们喜欢unnest 而不是stack,并且主要使用来自tidyr/dplyr 的函数使其更具吸引力: -)
  • 或者,实际上,unnest(dat,col) 将其保存在 tidyr/dplyr 中 :) 无需重命名
  • @Frank 但是,在sparseMatrix 中,我需要数字索引。例如。 d1 &lt;- unnest(dat,col) %&gt;% separate(x, into=c('row', 'val'), ':', convert=TRUE)。然后我可以使用sub 提取数字部分并转换为数字索引
  • 哦,问题是unnest 的行为与stringsAsFactors=FALSE 一致。这有效:d1 &lt;- stack(dat) %&gt;% separate(values, into=c('row', 'val'), ':', convert=TRUE) %&gt;% mutate(col=as.numeric(ind))。但这失败了:d1 &lt;- unnest(dat,col) %&gt;% separate(x, into=c('row', 'val'), ':', convert=TRUE) %&gt;% mutate(col=as.numeric(col))。当然,看起来不错:)
【解决方案2】:

解决方案:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-10
    • 2021-11-25
    • 2017-07-02
    • 2013-06-26
    • 1970-01-01
    • 1970-01-01
    • 2018-01-19
    • 1970-01-01
    相关资源
    最近更新 更多