10.4 Add Columns Using Variables

20200814 New columns can be added to a dataset where the new names are generated or supplied as the value of a variable. The example below uses uses the non-standard evaluation constructs and is generally useful when defining functions and the new variable name is passed through the function call. The notation includes the double exclamations (bang bang) which, technically, unquotes the following variable to replace it with its actual value. The colon equals is required in order to support unquoting the left hand side.

newvar <- "mid_temp"

ds %>%
  mutate(  newvar  = (max_temp + min_temp)/2,
         !!newvar := (max_temp + min_temp)/2) %T>%
  {
    select(., date, location, ends_with("_temp"), newvar) %>%
    sample_frac() %>%
    print()
  } ->
newds
## # A tibble: 176,747 x 6
##    date       location         min_temp max_temp mid_temp newvar
##    <date>     <chr>               <dbl>    <dbl>    <dbl>  <dbl>
##  1 2014-09-05 Uluru                14.5     20.2     17.4   17.4
##  2 2009-05-14 Bendigo               5.1     17.4     11.2   11.2
##  3 2014-02-03 Adelaide             23.6     28.3     26.0   26.0
##  4 2017-03-31 Adelaide              8.8     20.1     14.4   14.4
##  5 2013-04-19 AliceSprings         13.1     32.6     22.8   22.8
##  6 2019-07-19 PerthAirport         10.7     19.6     15.2   15.2
##  7 2015-08-09 WaggaWagga            0.6     12.8      6.7    6.7
##  8 2018-06-17 Townsville           15.3     24.7     20     20  
##  9 2018-09-07 MelbourneAirport      5.8     14.4     10.1   10.1
## 10 2018-09-09 NorahHead            10.7     22       16.4   16.4
## # … with 176,737 more rows


Your donation will support ongoing development and give you access to the PDF version of this book. Desktop Survival Guides include Data Science, GNU/Linux, and MLHub. Books available on Amazon include Data Mining with Rattle and Essentials of Data Science. Popular open source software includes rattle, wajig, and mlhub. Hosted by Togaware, a pioneer of free and open source software since 1984.
Copyright © 1995-2021 Graham.Williams@togaware.com Creative Commons Attribution-ShareAlike 4.0.