在 R 中,如何在另一个函数中使用引用函数?
In R, how can I use a quoting function inside another function?
我想弄清楚为什么 fun1()
有效但 fun2()
抛出错误。我认为这与 rlang
处理 x
变量的 quoting/unquoting 的方式有关,但我不太确定。这是一个玩具示例。我正在尝试围绕其他几个自定义引用函数创建一个包装器。
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()
,但这并没有帮助我找出问题。
我们可以使用 {{}}
作为列名:
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
我想弄清楚为什么 fun1()
有效但 fun2()
抛出错误。我认为这与 rlang
处理 x
变量的 quoting/unquoting 的方式有关,但我不太确定。这是一个玩具示例。我正在尝试围绕其他几个自定义引用函数创建一个包装器。
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()
,但这并没有帮助我找出问题。
我们可以使用 {{}}
作为列名:
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