我希望您能够翻译关于编程的中文内容。需要使用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)))
行不行? - akrunpurrr::map(x, purrr::compose(first, class))
或purrr::map(x, purrr::compose(~.[[1]], class))
。你不能从组合外部向组合内的不同部分传递不同的参数。 - MrFlick[[
,那么purrr::map(x, ~class(.x)[[1]])
也可以。你能发布你的答案吗?我会接受它。 - Indrajeet Patil