Go to TogaWare.com Home Page. Data Science Desktop Survival Guide
by Graham Williams
Duck Duck Go

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() %>%
  } ->
## # 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

Support further development by purchasing the PDF version of the book.
Other online resources include the GNU/Linux Desktop Survival Guide.
Books available on Amazon include Data Mining with Rattle and Essentials of Data Science.
Popular open source software includes rattle and wajig.
Hosted by Togaware, a pioneer of free and open source software since 1984.
Copyright © 2000-2020 Togaware Pty Ltd. . Creative Commons ShareAlike V4.