2

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

我的问题是,我们是否可以使用字符串操作函数substrstringr::str_remove内部.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.meanand Width.mean。为什么我要问,因为,这个论点的描述表明

.names
描述如何命名输出列的粘合规范。这可以使用 {.col} 代表选定的列名,使用 {.fn} 代表正在应用的函数的名称。对于单函数情况,默认值 (NULL) 等效于“{.col}”,对于 .fns 使用列表的情况,默认值 (NULL) 等效于“{.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所以我不关心那个答案。

4

1 回答 1

4

这可行,但可能有一些警告。您可以在胶水规范中使用函数,因此您可以通过这种方式清理字符串。但是,当我尝试转义 时".",我得到了一个错误,我认为这与如何across解析字符串有关。如果您需要更动态的东西,您可能想在那时深入研究源代码。

为了使用{.fn}帮助器,至少在像这样动态创建粘合字符串时,该函数需要一个名称;否则,您将在参数中获得函数索引的数字.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
于 2021-05-15T15:46:27.340 回答