我正在尝试按行名称对矩阵列表进行子集化。
mtx1 <- matrix(data = c(1:12), nrow = 4)
mtx2 <- matrix(data = c(13:24), nrow = 4)
row.names(mtx1) <- c("A", "B", "C", "D")
row.names(mtx2) <- c("A", "B", "C", "D")
my_list <- c("B", "D")
mtx_list <- list(mtx1, mtx2)
到目前为止,我已经尝试了
sub_mtx_list <- lapply(mtx_list, subset, row.names(mtx_list) %in% my_list)
我以为我会得到......
[[1]]
[,1] [,2] [,3]
B 2 6 10
D 4 8 12
[[2]]
[,1] [,2] [,3]
B 14 18 22
D 16 20 24
但我收到一组空的矩阵......
sub_mtx_list
[[1]]
[,1] [,2] [,3]
[[2]]
[,1] [,2] [,3]
非常感谢任何帮助!
答案 0 :(得分:1)
为了能够得到你期望的代码:
lapply(mtx_list,function(x) x[row.names(x)%in%c("B","D"),])
[[1]]
[,1] [,2] [,3]
B 2 6 10
D 4 8 12
[[2]]
[,1] [,2] [,3]
B 14 18 22
D 16 20 24
答案 1 :(得分:1)
无需使用subset
,您可以直接使用索引:
lapply(mtx_list, function(mat)mat[my_list,])
为您提供所需的输出:
[[1]]
[,1] [,2] [,3]
B 2 6 10
D 4 8 12
[[2]]
[,1] [,2] [,3]
B 14 18 22
D 16 20 24