我試圖弄清楚為什么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(),但這并沒有幫助我找出問題所在。
uj5u.com熱心網友回復:
我們可以{{}}用于列名:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/358109.html
