shayelk shayelk - 29 days ago 10
R Question

R - extracting a list element by name when the name is in a variable

I'm trying to extract a list element by name, when the name is stored in a variable. i.e.:

myList <- list(a = 1, b = 2, c = 3) ## list definition
## I can extract the second element like this:
myList$b
## but say I have a variable:
to_extract <- "b"
##can I do something like this?
myList$to_extract


Thanks!

ycw ycw
Answer Source

The following should all work.

myList[[to_extract]]

`[[`(myList, to_extract)

library(purrr)
pluck(myList, to_extract)