Templating knitr documents

June 23, 2015

Code chunks should be minimized with options for customization that reduce overall requirements for repetition.

Note: remove \ before triple backticks. It's only there for display purposes (otherwise it breaks the display of code).

Function

basic_plot_rmd <- function(data,title,new_levels = NULL,flip = NULL, title_level = 2, base_note = FALSE, kable_included = TRUE) {  
  title_adjusted <- gsub(" ","_",title)
  title_adjusted <- gsub("'","",title)
  adjust_levels <- length(new_levels) > 0
  if(length(new_levels) > 0) {
    data$Response <- new_levels
  }
  if(is.null(flip)) {
    adjust <- "vjust"
  } else {
    adjust <- "hjust"
  }
  if(!is.null(flip)){
    flip = "+ coord_flip()"
  }
  title_level <- paste0(rep("#",title_level),collapse = "")
  if(base_note) {
    base_note <- paste0("n = ",surv.sqa(data)$base)
  } else {
    base_note <- NULL
  }
  if(kable_included) {
    kable_included = "kable(data, row.names = FALSE)"
  }

  res = unlist(knit_expand(
    file = "path/to/basic_bar.Rmd", # CHANGE ME
    "title" = title,
    "title_adjusted" = title_adjusted,
    "data" = "data",
    "flip" = flip,
    "adjust" = adjust,
    "base_note" = base_note,
    "kable_included" = kable_included
  ))
  cat(knit(text = unlist(res), quiet = TRUE))
}

Rmd Template

{{title_level}} {{title}}

\```{r {{title_adjusted}}}

ggplot({{data}}, aes(Response, Proportion, label = label_fun(Proportion))) +  
  geom_bar(stat = "identity") +
  geom_text({{adjust}} = 2) +
  labs(x = "", y="") +
  scale_y_continuous(labels = percent) {{flip}}

{{kable_included}}
\```

{{base_note}}

Bringing it Together in a knitr Document

\```{r decisionmaker} 
basic_plot_rmd(  
  data = sums$DECISIONMAKER, 
  title = "Decision Maker", 
  new_levels = c("Yes","No","I would be","I influence")
  )
\```