Using wrapr::let() with tidyeval
[This article was first published on R – Win-Vector Blog, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
While going over some of the discussion related to my last post I came up with a really neat way to use wrapr::let()
and rlang
/tidyeval
together.
Please read on to see the situation and example.Suppose we want to parameterize over a couple of names, one denoting a variable coming from the current environment and one denoting a column name. Further suppose we are worried the two names may be the same.
We can actually handle this quite neatly, using rlang
/tidyeval
to denote intent (in this case using “!!
” to specify “take from environment instead of the data frame”) and allowing wrapr::let()
to perform the substitutions.
suppressPackageStartupMessages(library("dplyr")) library("wrapr") mass_col_name = 'mass' mass_const_name = 'mass' mass <- 100 let( c(MASS_COL = mass_col_name, MASS_CONST = mass_const_name), starwars %>% transmute(height, (!! MASS_CONST), # `mass` from environment MASS_COL, # `mass` from data.frame h100 = height * (!! MASS_CONST), # env hm = height * MASS_COL # data ) %>% head() ) #> # A tibble: 6 x 5 #> height `(100)` mass h100 hm #> <int> <dbl> <dbl> <dbl> <dbl> #> 1 172 100 77 17200 13244 #> 2 167 100 75 16700 12525 #> 3 96 100 32 9600 3072 #> 4 202 100 136 20200 27472 #> 5 150 100 49 15000 7350 #> 6 178 100 120 17800 21360
All in all, that is pretty neat.
To leave a comment for the author, please follow the link and comment on their blog: R – Win-Vector Blog.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.