如何在 dplyr::across 中的 .names 参数内使用字符串操作函数

2023-11-29

虽然我试图搜索它是否重复,但我找不到类似的问题。 (虽然一个similar那里有一个,但这与我的要求有些不同)

我的问题是我们是否可以使用字符串操作函数substr or stringr::str_remove inside .names的论证dplyr::across。作为一个可重现的例子,考虑这个

library(dplyr)
iris %>%
  summarise(across(starts_with('Sepal'), mean, .names = '{.col}_mean'))

  Sepal.Length_mean Sepal.Width_mean
1          5.843333         3.057333

现在我的问题是我想重命名输出列str_remove(.col, 'Sepal')这样我的输出列名称就是Length.mean and Width.mean。我为什么要问因为描述这个论点指出

.names
描述如何命名输出列的粘合规范。这可以使用 {.col} 代表选定的列名称,并使用 {.fn} 代表正在应用的函数的名称。默认值 (NULL) 相当于单函数情况下的“{.col}”,以及列表用于 .fns 的情况下的“{.col}_{.fn}”。

我尝试了很多可能性,包括以下内容,但这些都不起作用

library(tidyverse)
library(glue)
iris %>%
  summarise(across(starts_with('Sepal'), mean, 
                   .names = glue('{xx}_mean', xx = str_remove(.col, 'Sepal'))))

Error: Problem with `summarise()` input `..1`.
x argument `str` should be a character vector (or an object coercible to)
i Input `..1` is `(function (.cols = everything(), .fns = NULL, ..., .names = NULL) ...`.
Run `rlang::last_error()` to see where the error occurred.


#OR
iris %>%
  summarise(across(starts_with('Sepal'), mean, 
                   .names = glue('{xx}_mean', xx = str_remove(glue('{.col}'), 'Sepal'))))

我知道这可以通过添加另一个步骤来解决rename_with所以我不关心这个答案。


这可行,但可能有一些警告。您可以在粘合规范中使用函数,这样您就可以通过这种方式清理字符串。然而,当我试图逃避时".",我收到一个错误,我认为这与如何across解析字符串。如果您需要更动态的东西,您可能需要深入研究源代码。

为了使用{.fn}helper,至少与像这样动态创建粘合字符串一样,该函数需要一个名称;否则你会得到函数索引的数字.fns争论。我用第二个函数测试了这个并使用lst用于自动命名。

library(dplyr)
iris %>%
  summarise(across(starts_with('Sepal'), .fns = lst(mean, max), 
                   .names = '{stringr::str_remove(.col, "^[A-Za-z]+.")}_{.fn}'))
#>   Length_mean Length_max Width_mean Width_max
#> 1    5.843333        7.9   3.057333       4.4
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 dplyr::across 中的 .names 参数内使用字符串操作函数 的相关文章

随机推荐