【问题标题】:How to use string manipulation functions inside .names argument in dplyr::across如何在 dplyr::across 的 .names 参数中使用字符串操作函数
【发布时间】:2021-08-05 10:43:33
【问题描述】:

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

我的问题是我们是否可以在dplyr::across.names 参数中使用substrstringr::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.meanWidth.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',但是在解析时似乎有限制
  • 哦,是的!您能否将其发布为答案,我很乐意接受。 :)

标签: r dplyr across r-glue


【解决方案1】:

这可行,但可能有一些警告。您可以在胶水规范中使用函数,因此您可以通过这种方式清理字符串。但是,当我尝试转义"." 时,我收到了一个错误,我认为这与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

【讨论】:

  • summarise(across(starts_with("Sepal"), mean, .names = 'mean_{str_remove(.col, "Sepal.")}')) 适用于我的情况。谢谢:)
猜你喜欢
  • 2020-11-18
  • 1970-01-01
  • 1970-01-01
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-27
  • 1970-01-01
相关资源
最近更新 更多