使用 purrr 从以公共字母开头的多个列表中提取元素

using purrr to extract elements from multiple lists starting with a common letter

我有一个列表列表。每个列表中的一个元素的名称以 "n_" 开头。如何提取这些元素并将它们存储在单独的列表中?我可以使用 mapstarts_with 的组合吗?

例如:

m1 <- list(n_age = c(19,40,39),
       names = c("a", "b", "c"))

m2 <- list(n_gender = c("m","f","f"),
       names = c("f", "t", "d"))

nice_list <- list(m1, m2)

我希望像下面这样的东西能起作用(它不起作用!):

output <- map(nice_list, starts_with("n_"))

这个怎么样?

map(nice_list, ~.x[grep("n_", names(.x))])
#[[1]]
#[[1]]$n_age
#[1] 19 40 39
#
#
#[[2]]
#[[2]]$n_gender
#[1] "m" "f" "f"

或使用starts_with

map(nice_list, ~.x[starts_with("n_", vars = names(.x))])

或者要展平嵌套 list,您可以这样做

unlist(map(nice_list, ~.x[grep("n_", names(.x))]), recursive = F)
#$n_age
#[1] 19 40 39
#    
#$n_gender
#[1] "m" "f" "f"

您可以(滥用)使用 $:

的部分匹配
map(nice_list, `$`, "n_")

(我不是很推荐)

(而且我不明白为什么 lapply(nice_list, `$`, "n_") 不起作用(给出 list(NULL, NULL))。