How to extract lists within lists based on variable name in R

I have a list which I want to extract all sublists (matrices) with name a and store in a new list say matlist from the code below

x <- list()
x[[1]] <- list()
x[[2]] <- list()
x[[3]] <- list()

x[[1]]$a <- matrix(rnorm(4),2,2)
x[[1]]$b <- 3
x[[2]]$a <- matrix(rnorm(4),2,2)
x[[2]]$b <- 2
x[[3]]$a <- matrix(rnorm(4),2,2)
x[[3]]$b <- 1

Thank you in advance

Upvotes: 0

Views: 45

Answers (2)

Łukasz Deryło
Łukasz Deryło

Reputation: 1860

purrr::map is your friend:

library(purrr)
map(x, 'a')
[[1]]
           [,1]       [,2]
[1,] -0.9570164 -1.0893058
[2,] -1.5064699  0.5918877

[[2]]
           [,1]       [,2]
[1,]  0.5420939  1.5435010
[2,] -0.3326356 -0.1904059

[[3]]
          [,1]        [,2]
[1,]  1.892700  0.26731421
[2,] -1.735973 -0.08653999

Upvotes: 1

GKi
GKi

Reputation: 39647

You can use [[ in lapply with a to extract lists within lists based on variable name.

matlist <- lapply(x, "[[", "a")
matlist
#[[1]]
#          [,1]       [,2]
#[1,] 0.1232476 -0.2228539
#[2,] 0.4342695 -0.6379341
#
#[[2]]
#           [,1]      [,2]
#[1,] -0.4163436 -1.104486
#[2,] -2.3481197  1.523462
#
#[[3]]
#           [,1]       [,2]
#[1,]  0.1315805 -0.4286956
#[2,] -0.9083201  2.0258662

Upvotes: 1

Related Questions