r - R中按列名排列矩阵组列表的矩阵

标签 r list matrix

我有一个包含 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")

因此“组”由每个列名的姓氏标识,这里有 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)))

但我还没弄清楚具体怎么做。

最佳答案

#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

关于r - R中按列名排列矩阵组列表的矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45311224/

相关文章:

r - 如何使用 dplyr 计算嵌套数据框中的行数

r - 在 R 中使用 ggplot2 更改图例中的颜色

c++ - 将 future 存储在列表中

Haskell的民宿矩阵乘法错了?

python - 在python中填充/预测矩阵的未知值

r - R中的矩阵和向量乘法运算

datetime - 使用哪个 R 时间/日期类和包?

r - 如何精确地 grep 一个单词

python - 尝试将列表添加到列表时出现 TypeError

c++ - 是否可以在一行中创建一个 std::list 并指定其值(C++)?