Nicolas Molano
Nicolas Molano

Reputation: 734

subsetting in nested list r

I have the following list:

mylist<-list(c("25","0"),c("50","1"),c("100","2"))

And I want to extract at once the first element of each element on the list. That is

c(mylist[[1]][1],mylist[[2]][1],mylist[[3]][1])

I tried the following but without sucess:

mylist[[]][1]; mylist[[.]][1]; mylist[1:3][1]

I appreciate any suggestions to do this efficiently

Upvotes: 3

Views: 3589

Answers (2)

tyluRp
tyluRp

Reputation: 4768

Another lapply solution:

lapply(mylist,"[", 1)
[[1]]
[1] "25"

[[2]]
[1] "50"

[[3]]
[1] "100"

With purrr we could also do:

purrr::map(mylist, ~ .x[1])
[[1]]
[1] "25"

[[2]]
[1] "50"

[[3]]
[1] "100"

However, lapply should be faster.

Upvotes: 7

lefft
lefft

Reputation: 2105

If you want them as an atomic vector, you can use:

mylist <- list(c("25","0"),c("50","1"),c("100","2"))

sapply(mylist, function(v) v[1])
## [1] "25"  "50"  "100"

Or to get them as a list:

lapply(mylist, function(v) v[1])
## [[1]]
## [1] "25"
## [[2]]
## [1] "50"
## [[3]]
## [1] "100"

Upvotes: 3

Related Questions