Skip to content

Instantly share code, notes, and snippets.

@TysonStanley
Last active August 19, 2020 21:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TysonStanley/6fe3aefa1420b19be02d518b8f57902e to your computer and use it in GitHub Desktop.
Save TysonStanley/6fe3aefa1420b19be02d518b8f57902e to your computer and use it in GitHub Desktop.
``` r
library(tibble)
df = tibble(
var1 = rnorm(5),
var2 = rnorm(5)
)
first = function(data, x){
x = substitute(x)
eval(x, data)
}
wrap = function(data, x){
first(data, x)
}
wrap_working = function(data, x){
eval(substitute(first(data, x)))
}
first(df, var1)
#> [1] 2.4489749 -0.2397701 0.7707028 0.2790378 0.4131106
wrap(df, var1)
#> x
wrap_working(df, var1)
#> [1] 2.4489749 -0.2397701 0.7707028 0.2790378 0.4131106
```
<sup>Created on 2020-08-19 by the [reprex package](https://reprex.tidyverse.org) (v0.3.0)</sup>
@brodieG
Copy link

brodieG commented Aug 19, 2020

Here is an option that tries to better account for environments:

wrap_working2 = function(data, x){
  df <- identity   # a closure for an error
  var3 <- 42       # to illustrate bad lookup
  # `second` not visible in global env; doesn't have to be here, could
  # also be in a package namespace.
  second <- function(data, x){
    x = substitute(x)
    eval(x, data, parent.frame())
  }
  eval(
    bquote(.(second)(.(data), .(substitute(x)))),
    parent.frame()
  )
}
var3 <- 1               # we want to find this one
second <- stop          # if we find `second` in global -> error
wrap_working2(df, var1)
wrap_working2(df, var3)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment