【问题标题】:Matrix to list of matrix group by column names in R矩阵到 R 中按列名列出的矩阵组列表
【发布时间】:2017-07-25 18:40:59
【问题描述】:

我有一个包含 6000 列的矩阵,每列属于我需要的 100 个“组”之一。我需要将此矩阵转换为包含 100 个较小矩阵的列表。这是我所拥有的玩具示例:

  mat = cbind(c(2,2,2),c(3,3,3),c(4,4,4),c(1,1,1))
  colnames(mat) = c("2018.3 1","2018.3 2","2019.1 1","2019.2 2")

所以“组”由每个 colname 的姓氏标识,这里有 2 个组。我需要的结果如下:

list(cbind(c(2,2,2),c(4,4,4)),cbind(c(3,3,3),c(1,1,1)))

我一直在想,我觉得应该是这样的:

lapply(do.call(cbind,sapply(something here to find the columns in each group)))

但我还没有弄清楚到底该怎么做。

【问题讨论】:

    标签: r list matrix


    【解决方案1】:
    #Obtain the last part of each column names
    groups = sapply(strsplit(x = colnames(mat), split = " "), function(x) x[2])
    
    #Go through each unique column name and extract the corresponding columns
    lapply(unique(groups), function(x) mat[,which(groups == x)])
    #[[1]]
    #     2018.3 1 2019.1 1
    #[1,]        2        4
    #[2,]        2        4
    #[3,]        2        4
    
    #[[2]]
    #     2018.3 2 2019.2 2
    #[1,]        3        1
    #[2,]        3        1
    #[3,]        3        1
    

    lapply(split(1:NCOL(mat), sapply(strsplit(x = colnames(mat), split = " "),
                                     function(x) x[2])), function(i) mat[,i])
    #$`1`
    #     2018.3 1 2019.1 1
    #[1,]        2        4
    #[2,]        2        4
    #[3,]        2        4
    
    #$`2`
    #     2018.3 2 2019.2 2
    #[1,]        3        1
    #[2,]        3        1
    #[3,]        3        1
    

    【讨论】:

    • 你也可以groups <- sapply(strsplit(x = colnames(mat), split = " "), [, 2) or groups <- gsub(".*(\\d+)$","\\1", colnames(mat))
    猜你喜欢
    • 2011-08-10
    • 2017-04-22
    • 1970-01-01
    • 2017-05-03
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 2019-04-05
    • 2017-05-10
    相关资源
    最近更新 更多