我想知道如何使用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"我该怎么做?
发布于 2019-08-13 15:10:50
如果我们使用的是~,只需要包装first就可以得到预期的输出
library(purrr)
map(x, ~ first(class(.)))发布于 2019-08-13 15:37:33
来自?compose
组成(.,.dir =c(“向后”,“向前”) .函数按顺序应用(默认情况下从右到左),等等. .dir如果“向后”(默认),则按从右到左的相反顺序调用函数,这是数学中的惯例。如果“向前”,则从左到右调用它们。
所以我们只需要逆函数的顺序。而且,compose不知道i=1L属于哪个函数,所以compose会将它附加到最后一个函数(在本例中是class ),因此我们需要明确地定义i=1L到预期的函数。
purrr::map(.x = x, .f = purrr::compose(~.x[[1]], class))
[[1]]
[1] "data.frame"
[[2]]
[1] "tbl_df"
[[3]]
[1] "character"https://stackoverflow.com/questions/57480533
复制相似问题