Using two files (an r script and an rmarkdown script) we can create a series of reports. The following example creates five reports using the first five rows of the mtcars data. The rmarkdown file is called by the rscript one time for each unique car name in the subset of the mtcars data. An example of the reports produced by these files can be found here.

The rscript and rmarkdown script referenced in this tutorial can be found here along with the rmarkdown file that creates this tutorial.

File 1: R Script

# References for automation 

# File 1: Should be an R-Script 
    # contains a loop that iteratively calls an Rmarkdown file (i.e. File 2)

# load packages

# use first 5 rows of mtcars as example data
mtcars <- mtcars[1:5,]

# create map to plot data on (this is outside the loop so it is only called once)
map <-
  get_map(location="United States",
          source= 'google', maptype = 'terrain', color='bw', zoom=4) 

# for each type of car in the data create a report
  # these reports are saved in output_dir with the name specified by output_file
for (car in unique(rownames(mtcars))){
  rmarkdown::render('/Users/majerus/Desktop/R/auto_reporting/test/r_script.Rmd',  # file 2
                   output_file =  paste("report_", car, '_', Sys.Date(), ".html", sep=''), 
                   output_dir = '/Users/majerus/Desktop/R/auto_reporting/test/reports')

# for pdf reports  
#   rmarkdown::render(input = "/Users/majerus/Desktop/R/auto_reporting/test/r_script_pdf.Rmd", 
#           output_format = "pdf_document",
#           output_file = paste("test_report_", car, Sys.Date(), ".pdf", sep=''),
#           output_dir = "/Users/majerus/Desktop/R/auto_reporting/test/reports")

File 2: Rmarkdown

# run report for current car listed in loop in R file
cars <- mtcars[rownames(mtcars)==car,]

# create example data 
x <- sample(1:10, 1)
cars <-"rbind", replicate(x, cars, simplify = FALSE))

# create hypothetical lat and lon data 
cars$lat <- sapply(rownames(cars), function(x) round(runif(1, 30, 46), 3))
cars$lon <- sapply(rownames(cars), function(x) round(runif(1, -115, -80),3))

Today is 2015-04-22.

Today we sold cars to people in the following locations:

# map of cars sold
leaflet(cars) %>%
  addTiles() %>%
  setView(-93.65, 42.0285, zoom = 3) %>%
  addCircles(cars$lon, cars$lat) 

Here is a data table of the cars we sold.

# data table of cars sold 
datatable(cars[,c(1:2, 12:13)])

Here is a plot of mpg vs. weight for the sold cars:

# plot 
ggplot(cars, aes(mpg, wt)) + 
  geom_point(position = position_jitter(w = 0.1, h = 0.1)) + 
  stat_smooth(method="lm", se=TRUE)