Using wrapr::let() with tidyeval

June 28, 2017
By

(This article was first published on R – Win-Vector Blog, and kindly contributed to R-bloggers)

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
#>          
#> 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 on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Sponsors

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)