3

So I've found many times various different ways to achieve this, but as of the past year or so there have been changes to the way dplyr handles non standard evaluation. Essentially one way to achieve this is as follows:

require("dplyr")
test <- function(var){
  mtcars %>% select({{var}})
  print(quo_name(enquo(var)))
}

test(wt)
#> [1] "wt"

Is there a more direct way to achieve this as of 2021? I could have sworn there was something much simpler.

JoeTheShmoe
  • 433
  • 6
  • 13
  • You can use `glue` style strings inside of dplyr commands, bit if you need a `print()` outside of a dplyr chain I'm not sure there are better options. Might be better to avoid the double brace syntax in this case: `test <- function(var){var <- enquo(var); mtcars %>% select(!!var); print(quo_name(var))}` – MrFlick Jan 21 '21 at 20:41
  • Generally I have found the quosure system to be very complicated and to require a much deeper understanding of what's going on behind the scenes. I learned it at some point but I think it's too much overhead for the simple user, and my brain couldn't retain the info. I think even Hadley might have realized this too and why he's moved towards the double braces, and hence my question here. – JoeTheShmoe Jan 21 '21 at 21:31

2 Answers2

2

Use ensym() from rlang:

require("dplyr")
require("rlang")
test <- function(var){
    mtcars %>% select({{var}})
    print(ensym(var))
}

test(wt)
#>wt

as.character(test(wt))
#>wt
#>[1] "wt"
  • 1
    Is using ensym a similar concept to using `enquo` and `quo_name`? – JoeTheShmoe Jan 21 '21 at 21:34
  • 1
    It gets the name (as class 'name') in a single step (which would let you print it for informational purposes), but the class still requires coercion to a character (i.e. if you want to use it as a string). enquo returns a quosure, which is more useful if you want to go on to evaluate it as an object, but less useful for just getting the name IMO. – Matthew Skiffington Jan 21 '21 at 22:05
0

We can use deparse/substitute in base R

test <- function(var) deparse(substitute(var))

test(wt)
#[1] "wt"
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Could you update your answer using the same test function from the answer above? I seem to remember when I've tried this approach in the past there was some tricky nuance about it, maybe related to this question: https://stackoverflow.com/questions/47904321/deparsesubstitute-returns-function-name-normally-but-function-code-when-cal – JoeTheShmoe Jan 21 '21 at 21:39
  • @JoeTheShmoe You may use `as_string(ensym(var))` – akrun Jan 21 '21 at 21:41