Skip to content

Instantly share code, notes, and snippets.

@seasmith
Created July 7, 2019 01:33
Show Gist options
  • Save seasmith/edf212684fa1bdd66f3f48eb150ccdea to your computer and use it in GitHub Desktop.
Save seasmith/edf212684fa1bdd66f3f48eb150ccdea to your computer and use it in GitHub Desktop.
Examination of tidyeval's quosure
library(rlang)
# Underneath the hood of a quosure ------------------------------------
v <- "a variable"
vquo <- quo(v)
print(vquo)
#> <quosure>
#> expr: ^v
#> env: global
class(vquo)
#> [1] "quosure" "formula"
typeof(vquo)
#> [1] "language"
unclass(vquo)
#> ~v
#> attr(,".Environment")
#> <environment: R_GlobalEnv>
# Evaluating a quosure ----------------------------------------------------
# Persistent un-evalability (turns eval() into quote())
vquo_env <- attr(vquo, ".Environment")
eval(vquo, envir = vquo_env)
#> <quosure>
#> expr: ^v
#> env: global
# Symbolic expressions (i.e. ~v) are subsettable
length(vquo)
#> [1] 2
vquo[[1L]]
#> `~`
vquo[[2L]]
#> v
class(vquo[[2L]])
#> [1] "name"
# Take advantage of this to evaluate our symbol/call
eval(vquo[[2L]], envir = vquo_env)
#> [1] "a variable"
# Further exploration -----------------------------------------------------
a <- 5
b <- 6
abquo <- quo(a + b)
abquo_env <- attr(abquo, ".Environment")
evalq(abquo[[2L]], envir = abquo_env)
#> [1] 11
evalq(abquo[[2L]], envir = abquo_env)
#> a + b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment