首页 > 解决方案 > 按行名过滤矩阵的嵌套列表

问题描述

我有一个矩阵列表,该列表已被网络抓取。我希望按行名和列名过滤每个矩阵。我可以按行名和列表过滤矩阵,但不能按列表中的矩阵过滤!

一些数据

set.seed(1)

a_matrix  <-  matrix(sample(0:100, 16), ncol=4)
b_matrix <- matrix(sample(0:100, 16), ncol=4)
dimnames(a_matrix) <- list(rownames(a_matrix, do.NULL = FALSE, prefix = "row"),
                          colnames(a_matrix, do.NULL = FALSE, prefix = "col"))

dimnames(b_matrix) <- list(rownames(b_matrix, do.NULL = FALSE, prefix = "row"),
                           colnames(b_matrix, do.NULL = FALSE, prefix = "col"))
a_matrix
      col1 col2 col3 col4
row1   26   19   58   61
row2   37   86    5   33
row3   56   97   18   66
row4   89   62   15   42

b_matrix
      col1 col2 col3 col4
row1   13   21   86   12
row2    1   77   93   39
row3   44   64   74   47
row4   17   69   80   22

my_list <- list(a_matrix,b_matrix)


Filtering the whole list by:
 
names <- c("col1", "col2", "row2", "row3")

理想结果

a_matrix
      col1 col2  
row2   37   86   
row3   56   97   


b_matrix
      col1 col2 
row2    1   77   
row3   44   64  

虽然仍然保留在列表中。

标签: rlistmatrixfiltersubset

解决方案


list在with 上循环,使用向量中的lapply行/列名子集矩阵,names其中元素 3 到 4 是行名属性,1 到 2 是列名

lapply(my_list, \(x) x[names[3:4], names[1:2]])

-输出

[[1]]
     col1 col2
row2   37   86
row3   56   97

[[2]]
     col1 col2
row2    1   77
row3   44   64

数据

my_list <- list(structure(c(26L, 37L, 56L, 89L, 19L, 86L, 97L, 62L, 58L, 
5L, 18L, 15L, 61L, 33L, 66L, 42L), .Dim = c(4L, 4L), .Dimnames = list(
    c("row1", "row2", "row3", "row4"), c("col1", "col2", "col3", 
    "col4"))), structure(c(13L, 1L, 44L, 17L, 21L, 77L, 64L, 
69L, 86L, 93L, 74L, 80L, 12L, 39L, 47L, 22L), .Dim = c(4L, 4L
), .Dimnames = list(c("row1", "row2", "row3", "row4"), c("col1", 
"col2", "col3", "col4"))))

推荐阅读