littleworth
littleworth

Reputation: 5169

How to access specific named list inside nested list in R

I have the following nested list:

foo <- list(list(x = 1:10, y = 11:25), list(x = 1:10, y = 100:110))

It looks like this:

> foo
[[1]]
[[1]]$x
 [1]  1  2  3  4  5  6  7  8  9 10

[[1]]$y
 [1] 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25


[[2]]
[[2]]$x
 [1]  1  2  3  4  5  6  7  8  9 10

[[2]]$y
 [1] 100 101 102 103 104 105 106 107 108 109 110

What I want to do is only to access the y part of the list yielding in the object that contain this:

 [[1]]
 [1] 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25


[[2]]
 [1] 100 101 102 103 104 105 106 107 108 109 110

How can I achieve that?

Upvotes: 3

Views: 90

Answers (4)

ThomasIsCoding
ThomasIsCoding

Reputation: 101064

Here is another base R solution, using unlist() and subset

res <- subset(z<-unlist(foo,recursive = F),names(z)=="y")

such that

> res
$y
 [1] 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

$y
 [1] 100 101 102 103 104 105 106 107 108 109 110

Upvotes: 0

cimentadaj
cimentadaj

Reputation: 1488

A somewhat different solution is to transpose the list and access the slot:

foo <- list(list(x = 1:10, y = 11:25), list(x = 1:10, y = 100:110))
purrr::transpose(foo)$y
#> [[1]]
#>  [1] 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#> 
#> [[2]]
#>  [1] 100 101 102 103 104 105 106 107 108 109 110

Upvotes: 1

Łukasz Deryło
Łukasz Deryło

Reputation: 1860

One another option:

library(purrr)

map(foo, 'y')
[[1]]
 [1] 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

[[2]]
 [1] 100 101 102 103 104 105 106 107 108 109 110

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388817

We can use lapply

lapply(foo, `[[`, 'y')

#[[1]]
# [1] 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

#[[2]]
# [1] 100 101 102 103 104 105 106 107 108 109 110

Or pluck from rvest

rvest::pluck(foo, 'y')

Upvotes: 3

Related Questions