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
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With