虽然我试图搜索它是否重复,但我找不到类似的问题。 (虽然一个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
所以我不关心这个答案。