How to get the name of variable in NSE with dplyr

Viewed 143

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.

2 Answers

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"

We can use deparse/substitute in base R

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

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