R - 当名称在变量中时,按名称提取列表元素

时间:2017-09-24 15:27:36

标签: r list

当名称存储在变量中时,我正在尝试按名称提取列表元素。即:

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

谢谢!

1 个答案:

答案 0 :(得分:2)

以下都应该有效。

myList[[to_extract]]

`[[`(myList, to_extract)

library(purrr)
pluck(myList, to_extract)