【发布时间】:2019-12-20 04:12:06
【问题描述】:
我想知道如何使用purrr::map,其中.f 是两个不同函数的组合。
首先,让我们创建一个用于映射复合函数的列表:
library(tidyverse)
# create a list
x <- list(mtcars, tibble::as_tibble(iris), c("x", "y", "z"))
# extracting class of objects
purrr::map(.x = x, .f = class)
#> [[1]]
#> [1] "data.frame"
#>
#> [[2]]
#> [1] "tbl_df" "tbl" "data.frame"
#>
#> [[3]]
#> [1] "character"
现在假设我要提取列表中每个元素的class 的第一个元素:
# this works but uses `map` twice
purrr::map(.x = x, .f = class) %>%
purrr::map(.x = ., .f = `[[`, i = 1L)
#> [[1]]
#> [1] "data.frame"
#>
#> [[2]]
#> [1] "tbl_df"
#>
#> [[3]]
#> [1] "character"
这行得通,但我想避免使用map 两次,并且想编写一个可以一步提取类及其第一个元素的函数。所以我尝试编写这样一个函数,但它不能很好地与map
# error
purrr::map(.x = x, .f = purrr::compose(class, `[[`, i = 1L))
#> Can't convert an integer vector to function
# no error but not the expected output
purrr::map(.x = x, .f = purrr::compose(class, `[[`), i = 1L)
#> [[1]]
#> [1] "numeric"
#>
#> [[2]]
#> [1] "numeric"
#>
#> [[3]]
#> [1] "character"
我该怎么做?
【问题讨论】:
-
不会
map(x, ~ first(class(.x)))工作 -
或使用 compose:
purrr::map(x, purrr::compose(first, class))或purrr::map(x, purrr::compose(~.[[1]], class))。您不能真正从组合外部将不同的参数传递给组合中函数的不同部分。 -
@akrun 成功了!如果我一心想要使用
[[,purrr::map(x, ~class(.x)[[1]])也可以。你能发布你的答案,我会接受。
标签: r functional-programming tidyverse purrr