Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

r - 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.

question from:https://stackoverflow.com/questions/65835280/how-to-get-the-name-of-variable-in-nse-with-dplyr

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...