3

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?

0

4 Answers 4

3

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')
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.