Use {{ with two variables on a mutate

Hello,

I'm working on an internal package, and we pass a lot of variables in the parameters of our functions. With the previous version of rlang, we didn't find any other options than pass them as quosure, with vars(). Since the last version of rlang (with the curly-curly) and all the tidyselect functions, we've decided to pass the variables through vectors of string directly. Almost everything works well (select, group_by, distinct, rename, etc), except when we have two parameters (one for each variable) and try to use a function with those two variables in a mutate.

Here is an example that works well, but we want to remove the !! and use {{ if possible :

my_function <- function(mydata, var1, var2){
    mydata %>%
        mutate(difference = !!sym(var1) - !!sym(var2))
        # mutate(difference = {{var1}} - {{var2}}) NOT WORKING
}
head(my_function(iris, "Sepal.Length", "Petal.Length"))

Is there a way to do this ? I know the solution might be with across(), but it works only across one variable at a time, not more than one, right ?

Yes, @Yarnabrina is right. The vars should be called without double quoting them. Plus, you get the "autocompletion" when you pipe into your function


my_function <- function(mydata, var1, var2){
  mydata %>%
    mutate(difference = {{var1}} - {{var2}}) 
}

iris %>% 
  my_function(Sepal.Length, Petal.Length) %>%
  select(difference) %>% 
  head() 
#>   difference
#> 1        3.7
#> 2        3.5
#> 3        3.4
#> 4        3.1
#> 5        3.6
#> 6        3.7

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.