Created
May 30, 2015 20:27
-
-
Save garyfeng/16d0b498a919a1b77b7e to your computer and use it in GitHub Desktop.
R tricks with lazyeval::interp():
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# taken from | |
# http://cran.rstudio.com/web/packages/dplyr/vignettes/nse.html | |
# What if you need to mingle constants and variables? Use the handy lazyeval::interp(): | |
library(lazyeval) | |
# Interp works with formulas, quoted calls and strings (but formulas are best) | |
interp(~ x + y, x = 10) | |
#> ~10 + y | |
interp(quote(x + y), x = 10) | |
#> 10 + y | |
interp("x + y", x = 10) | |
#> [1] "10 + y" | |
# Use as.name if you have a character string that gives a variable name | |
interp(~ mean(var), var = as.name("mpg")) | |
#> ~mean(mpg) | |
# or supply the quoted name directly | |
interp(~ mean(var), var = quote(mpg)) | |
#> ~mean(mpg) | |
Because every action in R is a function call you can use this same idea to modify functions: | |
interp(~ f(a, b), f = quote(mean)) | |
#> ~mean(a, b) | |
interp(~ f(a, b), f = as.name("+")) | |
#> ~a + b | |
interp(~ f(a, b), f = quote(`if`)) | |
#> ~if (a) b | |
If you already have a list of values, use .values: | |
interp(~ x + y, .values = list(x = 10)) | |
#> ~10 + y | |
# You can also interpolate variables defined in the current | |
# environment, but this is a little risky becuase it's easy | |
# for this to change without you realising | |
y <- 10 | |
interp(~ x + y, .values = environment()) | |
#> ~x + 10 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment