【问题标题】:R Populate matrix with a list of indicesR用索引列表填充矩阵
【发布时间】:2016-06-02 08:12:13
【问题描述】:

我尝试从包含矩阵 M 中必须等于 1 的索引的列表 pList 中创建一个邻接矩阵 M。 例如,M 是一个 10x5 矩阵 变量 pList 包含 5 个元素,每个元素都是一个索引向量

例子:

s <- list("1210", c("254", "534"), "254", "534", "364")
M <- matrix(c(rep(0)),nrow = 5, ncol = length(unique(unlist(s))), dimnames=list(1:5,unique(unlist(s))))

实际上,我过于简单的解决方案是在矩阵行上使用 for 循环的残酷解决方案:

for (i in 1:nrow(M)){
      M[i, as.character(s[[i]])] <- 1 
}

所以预期的结果是:

M
  1210 254 534 364
1    1   0   0   0
2    0   1   1   0
3    0   1   0   0
4    0   0   1   0
5    0   0   0   1

问题是我必须处理包含数千行的矩阵,并且需要太多时间。 我不是“申请”专家,但我想知道是否有更快的解决方案

谢谢

问候

【问题讨论】:

    标签: r matrix apply


    【解决方案1】:

    我们可以将list 转换为matrixrow/column 索引,使用该索引将'M' 中的元素分配为1。

    M[as.matrix(stack(setNames(s, seq_along(s)))[,2:1])] <- 1
    M
    #   1210 254 534 364
    #1    1   0   0   0
    #2    0   1   1   0
    #3    0   1   0   0
    #4    0   0   1   0
    #5    0   0   0   1
    

    或者不是使用stack 转换为data.frame,我们可以unlist 's' 来获取列索引,cbind 具有通过复制list 和@ 的序列创建的行索引每个list元素的987654330@(使用lengths)并将'M'中的元素分配给1。

    M[cbind(rep(seq_along(s), lengths(s)), unlist(s))] <- 1
    

    或者另一种选择是创建一个sparseMatrix

    library(Matrix)
    Un1 <- unlist(s)
    sparseMatrix(i = rep(seq_along(s), lengths(s)),
                 j=as.integer(factor(Un1, levels = unique(Un1))),
                 x=1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-06
      • 1970-01-01
      • 2014-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-27
      • 2014-07-28
      相关资源
      最近更新 更多