Home > Back-end >  Filter nested list of matrix by row name
Filter nested list of matrix by row name

Time:11-16

I have a list of matrix, which was webscraped. I am looking to filter each matrix by row and column name. I can filter matrix by rownames and lists but not matrix in a list!

Some data

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")

Ideal Result

a_matrix
      col1 col2  
row2   37   86   
row3   56   97   


b_matrix
      col1 col2 
row2    1   77   
row3   44   64  

Whilst still remaining in a list.

CodePudding user response:

Loop over the list with lapply, subset the matrix with row/column names from the names vector where the elements 3 to 4 are the row names attribute, and 1 to 2 are the column names

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

-output

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

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

data

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"))))
  • Related