2017-09-24 100 views
0

我试图在名称存储在变量中时按名称提取列表元素。即:R - 当名称位于变量中时按名称提取列表元素

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

'myList [to_extract]'会给你全部元素。 – Tunn

回答

1

以下都应该工作。

myList[[to_extract]] 

`[[`(myList, to_extract) 

library(purrr) 
pluck(myList, to_extract)