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