Select 使用矢量基于名称的多个列表元素

Select multiple list elements based on their names using a vector

我有一个包含命名元素的列表,名为 namedlist

我想select一些元素根据它们的名字,存储在一个向量中。

This post 告诉我如何对 select 单个 元素执行此操作:

namedlist <- list(c("fff", "gggg", "hhh"), c("xxx", "yyy", "zzz"), c("pp", "ooo"), c("lll"))
names(namedlist) <- c("AA", "BB", "CC", "DD")

# only select the element AA
namedlist[grep("AA", names(namedlist))]

但是,我想select 多个 列表中的元素。

我有我想要 select 存储在向量中的元素的名称,needed

needed <- c("AA", "DD")

但是,下面的代码不起作用:

namedlist[grep(needed, names(namedlist))]

我该怎么做?

感谢您的帮助!

使用下标:

namedlist[needed]
## $AA
## [1] "fff"  "gggg" "hhh" 
##
## $DD
## [1] "lll"

namedlist$AA
## [1] "fff"  "gggg" "hhh" 

namedlist[["AA"]] # same
## [1] "fff"  "gggg" "hhh" 

namedlist["AA"] # same except it returns a sublist
## $AA
## [1] "fff"  "gggg" "hhh"