Skip to content

Instantly share code, notes, and snippets.

@pteetor

pteetor/toyApp.R

Created Nov 20, 2015
Embed
What would you like to do?
Splitting an R application into modular parts
#
# This is a toy example of splitting an R application
# into three distinct parts:
#
# - Loading the data
# - Calculating the analytics
# - Rendering an RMarkdown document
#
# Note: The RMarkdown doc appears in a companion file, toyDoc.Rmd.
#
# The split is useful because it cleanly moduarizes
# the application. We can likely change one module
# (loading, calculating, or rendering) without breaking
# another module.
#
# Also, by separating the components, we can more easily
# debug each one. For example, by splitting the (potentially)
# complicated analytics from the rendering, we can debug
# it before and outside the RMarkdown document.
#
library(rmarkdown)
loadData = function() {
return(mtcars[,c("mpg", "disp", "wt")])
}
doAnalytics = function(data) {
model = lm(mpg ~ disp + wt, data=data)
list(theModel = model,
theData = data )
}
#
# This is the application's top-level code
#
data <- loadData()
analytics <- doAnalytics(data)
# By passing the 'analytics' list as the RMarkdown environment,
# we make its contents available to R code in the doc.
rmarkdown::render("toyDoc.Rmd", envir=analytics)
---
title: "Toy Report"
output: html_document
---
This study demonstrates the clear relationship in car design
between miles per gallon (*mpg*), displacement (*disp*), and
vehicle weight (*wt*).
# Linear model
```{r, echo=FALSE}
print(summary(theModel))
```
# Appendix: Sample data
```{r, results="asis", echo=FALSE}
knitr::kable(theData)
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.