How to subset a list of a list based on the name

Viewed 596

I am given a list of lists. I would like now to subset the list based on the names of the sublist.

 L1<-list("A"=matrix(c(1:4),2),"B"=matrix(c("a","b","c","d"),2))
 L2<-list("A"=matrix(c(5:8),2),"B"=matrix(c("u","v","w","x"),2))
 L<-list(L1,L2)

I would now like to select the elements of the sublist according to their name. E.g.

select_names <- c("A")

and obtain a list of lists, whereas the sublist now only contains the elements that have names belonging to 'select_names'. In this case it would be just the element "A":

[[1]]
[[1]]$`A`
     [,1] [,2]
[1,]    1    3
[2,]    2    4


[[2]]
[[2]]$`A`
     [,1] [,2]
[1,]    5    7
[2,]    6    8
2 Answers

We can Extract

library(purrr)
map(L, `[`, select_names)
#[[1]]
#[[1]]$A
#     [,1] [,2]
#[1,]    1    3
#[2,]    2    4


#[[2]]
#[[2]]$A
#     [,1] [,2]
#[1,]    5    7
#[2,]    6    8

Or using lapply

lapply(L, function(x) x[select_names])

Or without anonymous function call

lapply(L, `[`, select_names)

Self promotion. If one is open to using packages, I wrote up a convenience function in the developer version of manymodelr that achieves the same.

manymodelr::get_this(A,L)
[[1]]
     [,1] [,2]
[1,]    1    3
[2,]    2    4

[[2]]
     [,1] [,2]
[1,]    5    7
[2,]    6    8
Related