【发布时间】: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中,您不需要enquo或ensym。你可以改为dplyr::summarise({{x}} := sum({{x}}, na.rm = TRUE))。 -
@epi10 减少代码的好选择。但是,仍然需要 TarJae 的回答才能正常工作。
-
是的,我的建议不是为了解决您遇到的错误。
-
另外,如果你想返回一个标准的 R 数据帧(而不是一个 tibble),你可以使用
%>% as.data.frame,而不是%>% data.frame(., stringsAsFactors=FALSE)。stringsAsFactors在 R 4.0 中已经默认为 FALSE。