Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Select all Nth list Items from a list of list [duplicate]

Tags:

r

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"
like image 697
cuore RT Avatar asked Oct 31 '25 01:10

cuore RT


2 Answers

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))
like image 185
Ronak Shah Avatar answered Nov 01 '25 14:11

Ronak Shah


We can use pluck with map

library(tidyverse)
map(Lst, pluck, 2) %>% 
         unlist
#[1] "A" "B" "C" "D" "E" "F"
like image 34
akrun Avatar answered Nov 01 '25 15:11

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!