Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting a quosure to a string in R

Tags:

r

dplyr

rlang

I've been using quosures with dplyr:

library(dplyr)
library(ggplot2)

thing <- quo(clarity)
diamonds %>% select(!!thing)
print(paste("looking at", thing))

[1] "looking at ~" "looking at clarity"

I really want to print out the string value put into the quo, but can only get the following:

print(thing)

<quosure: global>

~clarity

print(thing[2])

clarity()

substr(thing[2],1, nchar(thing[2]))

[1] "clarity"

is there a simpler way to "unquote" a quo()?

like image 900
16 revs, 12 users 31% Avatar asked Oct 25 '17 12:10

16 revs, 12 users 31%


2 Answers

We can use quo_name

print(paste("looking at", quo_name(thing)))
like image 169
akrun Avatar answered Oct 29 '22 01:10

akrun


If you use within a function, you will need to enquo() it first. Note also that with newer versions of rlang, as_name() seems to be preferred!

library(rlang)
fo <- function(arg1= name) {
  print(rlang::quo_text(enquo(arg1)))
  print(rlang::as_name(enquo(arg1)))
  print(rlang::quo_name(enquo(arg1)))
}

fo()  
#> [1] "name"
#> [1] "name"
#> [1] "name"
like image 34
Matifou Avatar answered Oct 29 '22 00:10

Matifou