syntheso
syntheso

Reputation: 447

Indexing named list with vector in R

How would you index the second element of a vector which is stored as a value in a named list?

I start with this:

hi <- list("1" = c("a","b"),
     "2" = c("dog","cat"),
     "3" = c("sister","brother")
     )

and would like to end up with a named list with the key plus the 2nd element of the vector i.e:

list("1" = "b",
     "2" = "cat",
     "3" = "brother"
     )

Upvotes: 2

Views: 655

Answers (2)

akrun
akrun

Reputation: 886948

We can use map

library(purrr)
map(hi, pluck, 2)
#$`1`
#[1] "b"

#$`2`
#[1] "cat"

#$`3`
#[1] "brother"

Upvotes: 0

tmfmnk
tmfmnk

Reputation: 39858

You can do:

lapply(hi, `[`, 2)

$`1`
[1] "b"

$`2`
[1] "cat"

$`3`
[1] "brother"

Upvotes: 2

Related Questions