如何将 .names 与 dplyr mutate across 和匿名函数一起使用

RDa*_*vey 8 r dplyr purrr

across()请参阅( https://dplyr.tidyverse.org/reference/across.html )的文档,您可以使用参数指定从 dplyr 动词返回的名称.names。可视化

iris %>%
  group_by(Species) %>%
  summarise(across(starts_with("Sepal"), mean, .names = "mean_{.col}"))
#> `summarise()` ungrouping output (override with `.groups` argument)
#> # A tibble: 3 x 3
#>   Species    mean_Sepal.Length mean_Sepal.Width
#>   <fct>                  <dbl>            <dbl>
#> 1 setosa                  5.01             3.43
#> 2 versicolor              5.94             2.77
#> 3 virginica               6.59             2.97
Run Code Online (Sandbox Code Playgroud)

但是,当我使用 purr 风格的匿名函数时,我收到一个错误:

iris %>% 
   group_by(Species) %>%
   mutate(across(contains(".Width"), ~.x - mean(.x), .names = "residual_{.col}"))

#> Error: Problem with `mutate()` input `..1`.
#> x glue cannot interpolate functions into strings.
#> * object '.col' is a function.
#> i Input `..1` is `across(contains(".Width"), ~.x - mean(.x), .names = "residual_{.col}")`.
#> i The error occured in group 1: Species = "setosa".
#> Run `rlang::last_error()` to see where the error occurred.
Run Code Online (Sandbox Code Playgroud)

删除.names参数即可消除错误。如何across在具有匿名函数的 dplyr 动词中使用指定名称?

小智 8

尝试删除 中的点.col,因此它将是:.names = "residual_{col}"

  • [文档](https://dplyr.tidyverse.org/reference/across.html#arguments)似乎表明您确实需要点 (2认同)
  • 我发现有趣的是它可以与“{.col}”(按定义)和“{col}”一起使用。听起来像是一个错误或未记录的容忍度。 (2认同)