使用 purrr 从以公共字母开头的多个列表中提取元素 [英] using purrr to extract elements from multiple lists starting with a common letter

查看:34
本文介绍了使用 purrr 从以公共字母开头的多个列表中提取元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a list of lists. One element in each list has a name beginning with "n_". How do I extract these elements and store them in a separate list? Can I use a combination of map and starts_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)

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

I was hoping that something like the following to work (it doesn't!):

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,你可以这样做

Or to flatten the nested list, you could do

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

这篇关于使用 purrr 从以公共字母开头的多个列表中提取元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆