Search code examples
rtidyeval

Using glue-like constructs on RHS in R/Tidyeval


I've spent hours trying to make glue on the RHS of a formula work and out of clues. Here is a simple reprex.

meta <- function(x, var, suffix){
  x<- x %>% mutate("{{var}}_{suffix}":= 5)
  
  x<- x %>% mutate("{{var}}_{suffix}_new":= {{var}} - "{{var}}_{suffix}")
  
  
}

x<- meta(mtcars, mpg, suf)

#Should be equivalent to

x<- mtcars %>% mutate(mpg_suf:= 5)

x<- x%>% mutate(mpg_suf_new:= mpg - mpg_suf)

#N: Tried https://stackoverflow.com/questions/70427403/how-to-correctly-glue-together-prefix-suffix-in-a-function-call-rhs but none of the methods in it worked, unfortunately

Meta function gives me "Error in local_error_context(dots = dots, .index = i, mask = mask) : promise already under evaluation: recursive default argument reference or earlier problems? "

Went over all hits for the searchwords for it on SO but nothing worked at the moment.

Would really appreciate any insights. Thank you!


Solution

  • Here is a working version:

    meta <- function(x, var, suffix){
      new_name <- rlang::englue("{{ var }}_{{ suffix }}")
      x %>%
        mutate("{new_name}" := 5) %>%
        mutate("{new_name}_new" := {{ var }} - .data[[new_name]])
    }
    
    names(meta(mtcars, mpg, suf))
    #>  [1] "mpg"         "cyl"         "disp"        "hp"
    #>  [5] "drat"        "wt"          "qsec"        "vs"
    #>  [9] "am"          "gear"        "carb"        "mpg_suf"
    #> [13] "mpg_suf_new"
    

    To understand what is going on:

    See also the general topic: https://rlang.r-lib.org/reference/topic-data-mask-programming.html