2017-09-24 102 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)