Suppose having a list of list made by this code :
Lst<-list(list(c(1,2,3),c('A','B','C')),
list(c(4,5,6),c('D','E','F')))
>Lst
[[1]]
[[1]][[1]]
[1] 1 2 3
[[1]][[2]]
[1] "A" "B" "C"
[[2]]
[[2]][[1]]
[1] 4 5 6
[[3]]
[1] "D" "E" "F"
How to extract all the seconds elements of all sub-lists (Lst[[1]][2] and Lst[[2]][2])to get this output :
> [1] "A" "B" "C" "D" "E" "F"
Use sapply over Lst
c(sapply(Lst, `[[`, 2))
#[1] "A" "B" "C" "D" "E" "F"
Or using purrr
library(purrr)
flatten_chr(map(Lst, 2))
We can use pluck with map
library(tidyverse)
map(Lst, pluck, 2) %>%
unlist
#[1] "A" "B" "C" "D" "E" "F"
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