Created
November 20, 2015 14:01
-
-
Save pteetor/c79b4525c49de40c8b5b to your computer and use it in GitHub Desktop.
Splitting an R application into modular parts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# 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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
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