How to print variable name from function argument using {{}} in R?

883 Views Asked by At

I am new to R and trying to understand functional Programming and use of {{}}.

I am not able to figure out how to just print the name of variable_name from argument without !!, enquos

I have tried below code but that doesn't work as expected:

summarise_min <- function(data, var_min, var_group) {

  print({{var_min}})
  
  print(glue("test_{{var_min}}"))

}

summarise_min(mtcars, mpg, cyl)

Have looked at some examples from : https://dplyr.tidyverse.org/articles/programming.html but its implementation is mostly in summarise / group functions:

my_summarise5 <- function(data, mean_var, sd_var) {
  data %>% 
    summarise(
      "mean_{{mean_var}}" := mean({{ mean_var }}), 
      "sd_{{sd_var}}" := mean({{ sd_var }})
    )
}
my_summarise5(mtcars, mpg, cyl)

I am trying to avoid use of !!, enquo, quo_name as they are very confusing.

Is there no way to work this out just by using {{}} and are they only limited to summarise functions?

1

There are 1 best solutions below

0
On BEST ANSWER

{{ works exclusively in tidyverse data-masking functions. print() and glue() are not such functions.

You can do print(enquo(var)). This (1) defuses var and prevents it from being evaluated; (2) prints the defused expression.

You could also create your own function to print a variable by wrapping this pattern:

print_arg <- function(arg) print(enquo(arg))

Since it uses the tidy eval operator enquo(), it automatically supports {{. You can call it like this:

print_arg({{ some_arg }})