Home > Back-end >  In R, how can I use a quoting function inside another function?
In R, how can I use a quoting function inside another function?

Time:11-17

I am trying to figure out why fun1() works but fun2() throws an error. I think it has something to do with the way in which rlang handles the quoting/unquoting of the x variable, but I'm not really sure. This is a toy example. I am trying to create a wrapper around several other custom quoting functions.

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.

I did check rlang::last_error() and rlang::last_trace(), but that did not help me figure out the issue.

CodePudding user response:

We could use {{}} for column names:

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
  • Related