converting a quosure to a string in R

早过忘川 提交于 2020-01-23 05:48:27

问题


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()?


回答1:


We can use quo_name

print(paste("looking at", quo_name(thing)))



回答2:


quo_name does not work if the quosure is too long:

> q <- quo(a + b + c + d + e + f + g + h + i + j + k + l + m + n + o + p + q + r + s + t + u + v + w + x + y + z)
> quo_name(q)
[1] "+..."

rlang::quo_text (not exported by dplyr) works better, but introduces line breaks (which can be controlled with parameter width):

> rlang::quo_text(q)
[1] "a + b + c + d + e + f + g + h + i + j + k + l + m + n + o + p + \n    q + r + s + t + u + v + w + x + y + z"

Otherwise, as.character can also be used, but returns a vector of length two. The second part is what you want:

> as.character(q)
[1] "~"                                                                                                    
[2] "a + b + c + d + e + f + g + h + i + j + k + l + m + n + o + p + q + r + s + t + u + v + w + x + y + z"
> as.character(q)[2]
[1] "a + b + c + d + e + f + g + h + i + j + k + l + m + n + o + p + q + r + s + t + u + v + w + x + y + z"



回答3:


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"


来源:https://stackoverflow.com/questions/46932310/converting-a-quosure-to-a-string-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!