ruser-defined-functionstidyeval

how to avoid tidy evaluation (especially double curly brace) in user define function in r?


id <- 1:30
x<-rnorm(30,1,10)
y<-rnorm(30,1,10)

data<-data.frame(id,x,y)

add<-function(data,
              y_1,
              y_2){
  
 
 
    data<-dplyr::mutate(data,
           higher_one = dplyr::case_when(
      {{y_1}} > {{y_2}} ~ "1",
      {{y_1}} < {{y_2}} ~ "2",
      {{y_1}} == {{y_2}} ~ "equal"
    ))
}

data2<-add(data,x,y)

so, suggestions from my collaborator are:

  1. remove the curly double brace because it is a tidy evaluation. and use standard evaluation instead

however, if I remove that curly double brace, the function does not work at all.

with the curly double brace, it works. but my collaborator does not want this, so I want to make my function without curly double brace, but equivocal to current function


Solution

  • Instead of interpolating with {{, subset with .data:

    add <- function(data, y_1, y_2) {
      dplyr::mutate(
        data,
        higher_one = dplyr::case_when(
          .data[[y_1]] > .data[[y_2]] ~ "1",
          .data[[y_1]] < .data[[y_2]] ~ "2",
          .data[[y_1]] == .data[[y_2]] ~ "equal"
        )
      )
    }
    
    data2 <- add(data, "x", "y")