【发布时间】:2021-08-05 10:43:33
【问题描述】:
虽然我试图搜索它是否重复,但我找不到类似的问题。 (虽然有一个similar,但这与我的要求有些不同)
我的问题是我们是否可以在dplyr::across 的.names 参数中使用substr 或stringr::str_remove 等字符串操作函数。作为一个可重复的例子考虑这个
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 和 Width.mean 。为什么我要问,因为这个论点的description 指出
.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 添加另一个步骤来解决,所以我不关心那个答案。
【问题讨论】:
-
您可以在胶水字符串中使用函数,例如
.names = '{str_remove(.col, "^[A-Za-z]+")}_mean',但是在解析时似乎有限制 -
哦,是的!您能否将其发布为答案,我很乐意接受。 :)