Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 966
Nicolas Molano Avatar asked Apr 02 '26 09:04

Nicolas Molano


2 Answers

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.

like image 154
tyluRp Avatar answered Apr 08 '26 19:04

tyluRp


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"
like image 35
lefft Avatar answered Apr 08 '26 17:04

lefft