#R user group targets package coding demo library(targets) library(tidyverse) library(broom) #1. Write some basic functions ------------------------ import <- function(raw_data) {mtcars} clean <- function(imported_data) {filter(imported_data, mpg>20)} model <- function(cleaned_data) {tidy(lm(mpg ~ wt, data=cleaned_data))} visualise <- function(cleaned_data) {ggplot(aes(x=mpg, y=hp), data=cleaned_data) + geom_point() + geom_smooth()} #2. Run with pipes ----------------------------------- import() %>% clean() %>% model() import() %>% clean() %>% visualise() #3. Replace the piped code with a targets pipeline --------------------------- targets <- list( tar_target(imported_data, import()), tar_target(cleaned_data, clean(imported_data)), tar_target(model_data, model(cleaned_data)), tar_target(plots, visualise(cleaned_data)) ) #Run tar_visnetwork() #Run tar_make() #4 Change the clean function -------------------------------------- clean <- function(imported_data) {filter(imported_data, mpg>30)} #Run tar_visnetwork() #Run tar_make() #Run tar_visnetwork() #5 Change the model function, map()ing over formulas ---------------- model <- function(cleaned_data) { formulas <- c( "mpg ~ hp", "mpg ~ cyl", "mpg ~ drat") map(formulas, ~lm(.x, data=cleaned_data)) } #Run tar_make() #Run tar_visnetwork() #6 Add models as branching pattern ----------------------------------- # Add a new formulas target to the targets pipeline tar_target(formulas, c( "mpg ~ hp", "mpg ~ cyl", "mpg ~ drat")) # Change the model function to take formulas as well as data model <- function(cleaned_data, formulas) {tidy(lm(as.formula(formulas), data=cleaned_data))} # Change the model_data target to include formula and pattern=formulas tar_target(model_data, model(cleaned_data, formulas), pattern = formulas) #Run tar_make() #Run tar_visnetwork() # 7 Change one formula in the formulas target ----------------------------------- tar_target(formulas, c( "mpg ~ wt", "mpg ~ cyl", "mpg ~ drat")) #Run tar_visnetwork() #Run tar_make() #Run tar_visnetwork()