如何将函数参数粘贴到 dplyr 的跨函数中的 .names? [英] How to glue a function argument to .names in dplyr's across function?

查看:22
本文介绍了如何将函数参数粘贴到 dplyr 的跨函数中的 .names?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 {col}

I am trying to name the output of an across function using both {col} and one of the function arguments in

library(tidyverse)

mean_by <- function(data, by, var, prefix = "avg") {
  data %>% 
    group_by({{ by }}) %>% 
    summarise(across({{ var }}, mean, .names = "{prefix}_{col}"))
}

但是,在对 iris %>% mean_by(Species, Sepal.Width) 进行测试时,我收到无法找到对象前缀"的错误..names 中的粘合语法对我来说看起来没问题,所以我认为这是一个范围问题?.names 参数是否只能访问传递给 across 的内容?

However, when testing on iris %>% mean_by(Species, Sepal.Width), I get the error that object 'prefix' cannot be found. The glue syntax in .names looks okay to me so I assume this is a scoping issue? Can the .names argument only access what has been passed to across?

推荐答案

我相信 across 中的 .names 只允许引用 {col}> 和 {fn} 位于 across 内,但您可以尝试粘贴您的 prefix:

I believe .names in across only allow references to {col} and {fn} inside across, but you can try pasting your prefix:

> library(tidyverse)
> mean_by <- function(data, by, var, prefix = "avg") {
  data %>% 
    group_by({{ by }}) %>% 
    summarise(across({{ var }}, mean, .names = paste0(prefix,"_{col}")))
 }
> iris %>% mean_by(Species, Sepal.Width)
`summarise()` ungrouping output (override with `.groups` argument)
# A tibble: 3 x 2
  Species    avg_Sepal.Width
  <fct>                <dbl>
1 setosa                3.43
2 versicolor            2.77
3 virginica             2.97

这篇关于如何将函数参数粘贴到 dplyr 的跨函数中的 .names?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆