Skip to content

Instantly share code, notes, and snippets.

@DavisVaughan
Created June 21, 2019 21:30
Show Gist options
  • Save DavisVaughan/76770079624d66eaac2f15a5008bf439 to your computer and use it in GitHub Desktop.
Save DavisVaughan/76770079624d66eaac2f15a5008bf439 to your computer and use it in GitHub Desktop.
library(rlang)
library(purrr, warn.conflicts = FALSE)
a <- 2
b <- 5
fn_dots <- function(...) {
# capture `...` without evaluating
# (also captures the environment so we know how to
# evaluate them when the time comes)
dots <- enquos(...)
# `as_label()` can turn a quosure into a pretty string
# `eval_tidy()` will evaluate each one of your dots
list(
strings = map_chr(dots, as_label),
values = map_dbl(dots, eval_tidy)
)
}
# you have to pass in each element separately
fn_dots(0, a, (a + b) / 2, b, a + b)
#> $strings
#>
#> "0" "a" "(a + b)/2" "b" "a + b"
#>
#> $values
#>
#> 0.0 2.0 3.5 5.0 7.0
# If you want to use this outside a function you can play around with it
# with quos()
captured <- quos(0, a, (a + b) / 2, b, a + b)
captured
#> <list_of<quosure>>
#>
#> [[1]]
#> <quosure>
#> expr: ^0
#> env: empty
#>
#> [[2]]
#> <quosure>
#> expr: ^a
#> env: global
#>
#> [[3]]
#> <quosure>
#> expr: ^(a + b) / 2
#> env: global
#>
#> [[4]]
#> <quosure>
#> expr: ^b
#> env: global
#>
#> [[5]]
#> <quosure>
#> expr: ^a + b
#> env: global
map_dbl(captured, eval_tidy)
#>
#> 0.0 2.0 3.5 5.0 7.0
# there is no way to make the variable first
# and then try and capture the information
# because once you assign it to `steps` it has been evaluated!
steps <- c(0, a, (a + b) / 2, b, a + b)
# i.e. no way to recover a / b symbols at this point
steps
#> [1] 0.0 2.0 3.5 5.0 7.0
# the original example also had you going from
# c(0, a, (a + b) / 2, b, a + b) -> string version
# this is rather hard to do
fn_dots2 <- function(x) {
x <- enquo(x)
as_label(x)
}
# you can capture and label the whole thing
whole_string <- fn_dots2(c(0, a, (a + b) / 2, b, a + b))
# but then you'd have to use regex to split it apart :/
library(stringr)
str_split(str_sub(whole_string, 3, -2), ", ")
#> [[1]]
#> [1] "0" "a" "(a + b)/2" "b" "a + b"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment