JoeTheShmoe
JoeTheShmoe

Reputation: 485

How to get the name of variable in NSE with dplyr

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.

Upvotes: 3

Views: 451

Answers (2)

Matthew Skiffington
Matthew Skiffington

Reputation: 332

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"

Upvotes: 3

akrun
akrun

Reputation: 887108

We can use deparse/substitute in base R

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

test(wt)
#[1] "wt"

Upvotes: 0

Related Questions