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

岁酱吖の 提交于 2020-01-16 05:42:07

问题


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?

E.g.:

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_"))

回答1:


How about this?

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

Or using starts_with

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

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"



回答2:


You could (ab)use partial matching of $:

map(nice_list, `$`, "n_")

(I don't really recommend it).

(And I can't figure out why lapply(nice_list, `$`, "n_") doesn't work (gives a list(NULL, NULL)).



来源:https://stackoverflow.com/questions/50711333/using-purrr-to-extract-elements-from-multiple-lists-starting-with-a-common-lette

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!