Data Science Desktop Survival Guide
by Graham Williams |
|||||
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
|