【问题标题】:In R, how can I use a quoting function inside another function?在 R 中,如何在另一个函数中使用引用函数?
【发布时间】:2021-12-27 23:15:20
【问题描述】:

我试图弄清楚为什么fun1() 有效但fun2() 会引发错误。我认为这与rlang 处理x 变量的引用/取消引用的方式有关,但我不太确定。这是一个玩具示例。我正在尝试围绕其他几个自定义引用函数创建一个包装器。

fun1 <- function(df, x, ...){
    x_var <- rlang::enquo(x)
    x_name <- rlang::ensym(x)
    
  out <- df%>%
         dplyr::group_by(...)%>%
         dplyr::summarise(!!x_name:=sum(!!x_var, na.rm = TRUE))%>%
         dplyr::ungroup()%>%
         data.frame(., stringsAsFactors = FALSE)
   return(out)      
}

fun2 <- function(df, x, ...){
  out2 <- fun1(df = df, x=x, ...)
return(out2)
}

fun1(df = head(mtcars), x = mpg, cyl, disp, hp)

`summarise()` has grouped output by 'cyl', 'disp'. You can override using the `.groups` argument.
  cyl disp  hp  mpg
1   4  108  93 22.8
2   6  160 110 42.0
3   6  225 105 18.1
4   6  258 110 21.4
5   8  360 175 18.7

fun2(df = head(mtcars), x = mpg, cyl, disp, hp)

Error: Problem with `summarise()` column `x`.
i `x = sum(x, na.rm = TRUE)`.
x only defined on a data frame with all numeric-alike variables
i The error occurred in group 1: cyl = 4, disp = 108, hp = 93.
Run `rlang::last_error()` to see where the error occurred.

我确实检查了rlang::last_error()rlang::last_trace(),但这并没有帮助我找出问题所在。

【问题讨论】:

  • 我编辑了它。我对使用点还是很陌生,所以我不确定语法。但是,无论哪种方式,错误都是相同的。
  • fun1 中,您不需要enquoensym。你可以改为dplyr::summarise({{x}} := sum({{x}}, na.rm = TRUE))
  • @epi10 减少代码的好选择。但是,仍然需要 TarJae 的回答才能正常工作。
  • 是的,我的建议不是为了解决您遇到的错误。
  • 另外,如果你想返回一个标准的 R 数据帧(而不是一个 tibble),你可以使用%&gt;% as.data.frame,而不是%&gt;% data.frame(., stringsAsFactors=FALSE)stringsAsFactors 在 R 4.0 中已经默认为 FALSE。

标签: r dplyr rlang


【解决方案1】:

我们可以使用{{}} 作为列名:

fun2 <- function(df, x, ...){
  out2 <- fun1(df = df, x={{x}}, ...)
  return(out2)
}
  cyl disp  hp  mpg
1   4  108  93 22.8
2   6  160 110 42.0
3   6  225 105 18.1
4   6  258 110 21.4
5   8  360 175 18.7

【讨论】:

  • 天哪,如此简单......但我永远不会猜到!谢谢塔杰!您能否就 {{}} 背后的理念详细说明您的答案。它会帮助我,也许还有其他来这里寻求类似解决方案的人。
  • 您可以通过在函数体中的所需列名周围使用双花括号{{...}}直接访问数据帧的特定列,请查看此处r-bloggers.com/2019/06/curly-curly-the-successor-of-bang-bang>了解更多洞察力!
  • 太棒了。非常感谢 TarJae!
猜你喜欢
  • 1970-01-01
  • 2012-09-16
  • 1970-01-01
  • 1970-01-01
  • 2014-03-24
  • 2011-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多