shayelk
shayelk

Reputation: 1656

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!

Upvotes: 3

Views: 311

Answers (1)

www
www

Reputation: 39174

The following should all work.

myList[[to_extract]]

`[[`(myList, to_extract)

library(purrr)
pluck(myList, to_extract)

Upvotes: 3

Related Questions