【问题标题】:using purrr to extract elements from multiple lists starting with a common letter使用 purrr 从多个列表中提取以共同字母开头的元素
【发布时间】:2018-06-06 02:13:40
【问题描述】:

我有一个列表列表。每个列表中的一个元素的名称以“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_"))

【问题讨论】:

  • lapply(nice_list, function(x) x[grepl("^n_", names(x))]) in base R

标签: r tidyverse purrr


【解决方案1】:

你可以(ab)使用$的部分匹配:

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

(我真的不推荐)。

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

【讨论】:

  • 你能解释一下为什么你不推荐这个解决方案吗?目前它非常适合我的目的,但我想知道是否有任何我不了解的风险
  • 部分匹配是一种用于交互使用的功能。作为一般规则,我更喜欢按照开发人员计划的方式使用接口,以避免意外和脆弱的代码。我不明白的事实(为什么 lapply 在这里失败)也是一个危险信号。 lapply 是稳定的,但 purrr::map 可能会改变并破坏它。虽然如果它对你有用,只要你意识到它并小心......
【解决方案2】:

这个怎么样?

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"

【讨论】:

    猜你喜欢
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-22
    • 2021-04-08
    • 2016-04-17
    • 1970-01-01
    相关资源
    最近更新 更多