Skip to content

Instantly share code, notes, and snippets.

@mayrop
Last active January 3, 2020 23:20
Show Gist options
  • Save mayrop/2d144f5c8a87d2d11a860d3bfe791a91 to your computer and use it in GitHub Desktop.
Save mayrop/2d144f5c8a87d2d11a860d3bfe791a91 to your computer and use it in GitHub Desktop.
# https://thisisnic.github.io/2018/03/31/what-the-heck-is-quasiquotation/
> enquo(Species)
Error in (function (x) : object 'Species' not found
> quo(Species)
<quosure>
expr: ^Species
env: global
> my_test <- function(col) {
+ print(enquo(col))
+ print(quo(col))
+ }
> my_test(Species)
[1] "using > enquo(col)"
<quosure>
expr: ^Species
env: global
[1] "using > quo(col)"
<quosure>
expr: ^col
env: 0x5571aef68958
> sym("Species")
Species
# !! evaluates right away
> f1 <- function(x, y) {
+ exprs(x = x, y = y)
+ }
> f2 <- function(x, y) {
+ enexprs(x = x, y = y)
+ }
> f1(a + b, c + d)
$x
x
$y
y
> f2(a + b, c + d)
$x
a + b
$y
c + d
> x <- -1
> expr(f(x, y))
f(x, y)
> expr(f(!!x, y))
f(-1, y)
> expr(f(x, y))
f(x, y)
# Given the following components:
xy <- expr(x + y)
xz <- expr(x + z)
yz <- expr(y + z)
abc <- exprs(a, b, c)
# Use quasiquotation to construct the following calls:
substitute(x/y, list(x=xy, y=yz))
expr(!!xy / !!yz)
# (x + y) / (y + z)
substitute(-x ^ y, list(x=xy, y=yz))
expr(-(!!xy) ^ !!yz)
# -(x + z) ^ (y + z)
substitute((x) + y - z, list(x=xy, y=yz, z=xy))
expr(((!!xy)) + !!yz - (!!xy))
# (x + y) + (y + z) - (x + y)
substitute(atan2(x, y), list(x=xy, y=yz))
expr(atan2(!!xy, !!yz))
# atan2(x + y, y + z)
# wrong....
expr(atan2(!!!enquos(xy), !!!enquo(yz)))
atan2(~x + y, ~y + z)
substitute(sum(x, y, z), list(x=xy, y=xy, z=yz))
expr(sum(!!xy, !!xy, !!yz))
# sum(x + y, x + y, y + z)
substitute(sum(x), list(x=abc)) # sum(list(a, b, c))
expr(sum(!!!abc))
# sum(a, b, c)
#substitute(!!abc)
expr(mean(c(!!!abc), na.rm=TRUE))
# mean(c(a, b, c), na.rm = TRUE)
expr(foo(a=!!xy, b=!!yz))
# foo(a = x + y, b = y + z)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment