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: 275,410 × 6
##    date       location         min_temp max_temp mid_temp newvar
##    <date>     <chr>               <dbl>    <dbl>    <dbl>  <dbl>
##  1 2011-03-19 Dartmoor              9.6     22.9     16.2   16.2
##  2 2015-02-11 Sale                 16       35.1     25.6   25.6
##  3 2018-11-15 Darwin               22.4     33.7     28.0   28.0
##  4 2023-04-12 PerthAirport         14.5     23.9     19.2   19.2
##  5 2013-10-26 Ballarat              5.5     13.1      9.3    9.3
##  6 2025-12-06 SalmonGums            5.6     28       16.8   16.8
##  7 2011-01-10 Watsonia             18       26.1     22.0   22.0
##  8 2022-03-17 Townsville           24.6     32.9     28.8   28.8
##  9 2019-12-04 MelbourneAirport     10.4     23.4     16.9   16.9
## 10 2018-04-24 MountGambier         13.8     20.9     17.4   17.4
## # ℹ 275,400 more rows


If you find this curated material useful then you can consider a donation to support it's ongoing availability and give you access to the PDF version of this book. The material has been scoped up by Generative AI without permission or any kind of recompense so do consider a donation if you can afford it. Unlike Generative AI your access to this materials is freely given. Desktop Survival Guides include Data Science, GNU/Linux, and MLHub. Books available on Amazon include Data Mining with Rattle and Essentials of Data Science. Togaware has a 30 year tradition of making popular open source software which includes sold privacy preserving productivity apps, rattle, wajig, and mlhub. Hosted by Togaware, a pioneer of free and open source software since 1984. Copyright © 1995-2022 Graham.Williams@togaware.com Creative Commons Attribution-ShareAlike 4.0