r functions: knitr wrapper

Summary

Thought i'd share the wrapper function i use to knit files using the excellent knitr package in R. This allows easy creation of an html page that integrates commentary, R code, and the resulting plots (which are base64 encoded, so the html file is fully portable).

Thought i'd share the wrapper function i use to knit files using the excellent knitr package in R. This allows easy creation of an html page that integrates commentary, R code, and the resulting plots (which are base64 encoded, so the html file is fully portable). The code is pretty readable and commented, so i won't explain each part. Enjoy!

download knitr.compile.toHTML.R

R / S+
  1. # biafra ahanonu
  2. # updated: 2013.07.13
  3. # knitr wrapper function
  4. # ________________________________________________________
  5. # load libraries
  6. require(knitr)
  7. require(markdown)
  8. # ________________________________________________________
  9. flipExt <- function(input,ext){
  10.         # loop over and process files in the list
  11.         return(paste(c(head(unlist(strsplit(input,'\\.')),-1),ext),sep=".",collapse="."))
  12. }
  13. gsubFile <- function(file,pattern,replacement){
  14.         # substitute multiple patterns in a file, create temporary file to process
  15.         newFile = paste(file,'.tmp.Rmd',sep="")
  16.         for (i in 1:length(pattern)){
  17.                 fileContents <- readLines(file)
  18.                 modifiedContents <- gsub(pattern[i],replacement[i], fileContents)
  19.                 cat(modifiedContents, file=newFile, sep="\n")
  20.         }
  21.         return(newFile)
  22. }
  23. knitFileToHTML <-function(rmdFileList=c('TheFile.Rmd'), newDir="./"){
  24.         #knit files in newDir together, defaults to current directory
  25.         # move to folder with file
  26.         oldDir = getwd()
  27.         # cd to new directory
  28.         setwd(newDir)
  29.  
  30.         # knit that file!
  31.         for (rmdFile in rmdFileList){
  32.                 # so you can indent R blocks, also suppress warnings/error messages
  33.                 newRmdFile = gsubFile(rmdFile,c("\t```\\{r\\}","\t```"),c("```\\{r warning=FALSE, error=FALSE\\}","```"))
  34.                 # get html/md filenames
  35.                 mdFile = flipExt(newRmdFile,'md')
  36.                 htmlFile = flipExt(newRmdFile,'html')
  37.                 # knit to markdown
  38.                 knit(newRmdFile)
  39.  
  40.                 # extra html to add for style (prevent code/images from overflowing horizontal page boundaries)
  41.                 extraHtml = '<style>body{width:80%;margin-left:auto;margin-right:auto;}img,pre,code{white-space:pre-wrap;max-width:100%;margin-left:auto;margin-right:auto;}pre{border: 0px solid #ccc;}code.r{border: 1px solid #ccc;}div#toc{-moz-column-count: 4;-webkit-column-count: 4;-moz-column-gap: 1em;-webkit-column-gap: 1em;-moz-column-rule: 1px solid black;-webkit-column-rule: 1px solid black;}li{display:block;}</style>'
  42.                 # append extra html to markdown file
  43.                 write(extraHtml,file=mdFile,append=TRUE)
  44.  
  45.                 # convert to html
  46.                 markdownToHTML(file=mdFile,output=htmlFile,options=c('toc',"use_xhtml","smartypants","base64_images","mathjax","highlight_code"))
  47.  
  48.                 # remove md and temp Rmd file
  49.                 unlink(c(newRmdFile,mdFile))
  50.         }
  51.  
  52.         # return to old directory
  53.         setwd(oldDir)
  54. }
  55.  
  56. # run the script
  57. knitFileToHTML(rmdFileList=c('TheFile.Rmd'), newDir="./")

-biafra
bahanonu [at] alum.mit.edu

more articles to enjoy:

coding practices, part 1
10 december 2013 | programming

Some thoughts on coding practices and an outline of a work-flow that i find useful when starting any project. Future posts will focus on co[...]ncrete examples.

¿qué es la calle?
24 may 2013 | short story | spanish

Había terminado y salé para mi cocina. Tenía hambre pero este día no había comida dentro de mi despensa. Me fui y caminé hacienda[...] la Tport—una máquina que puede transportar una persona a otro lugar sin energía y tiempo. Cuando entré la máquina, toqué algunos botónes y esperé. Pero nada ocurrió y lo hice las mismas acciones otra vez—y nada ocurrió.

How would the disappearance of streets affect the social fabric? This short story briefly (in castellano!) explores a world in which instantaneous, free transport is possible. Meant mainly to practice my spanish, i plan to follow-up with a more detail story in the future.

book review — the road to serfdom
25 january 2017 | books

For those willing to take the plunge, The Road to Serfdom is endlessly rewarding and well worth the intellectual effort. A [...]re-post of a book review I did back in July 2008.

satellite-based videos: eastern europe during the russia-ukraine conflict
30 november 2022 | satellite

To visualize the nighttime lights of Eastern Europe, with a focus on times before and after the ongoing Russia-Ukraine conflict, I updated [...]my geoSatView R code originally built to view forest fires in the west coast of the United States to use satellite data from VNP46A1 and other datasets collected from the Suomi NPP VIIRS satellite.

I then created higher-quality movies in MATLAB by using the VNP46A2 Black Marble dataset collected by the same satellite, which has reduced cloud and other artifacts due to additional data processing. This allowed me to quantitate a permanent reduction in nighttime lights within Ukraine (in line with my initial hypothesis) and identify a multi-stage reduction of nighttime lights in Kiev's outer neighborhoods/metropolitan area that was greater than that seen in the city core/center. This highlights the utility of public satellite data to quickly test hypotheses and visualize large-scale changes.

I will go over how the Black Marble dataset is collected and processed along with how I created the movies and the advantages/disadvantages of each data source.

Using this platform and codebase, in follow-up posts I will look at 2021 Texas power crisis during the winter storms, vegetation changes in deforested areas or after conservation efforts, and other events.

©2006-2025 | Site created & coded by Biafra Ahanonu | Updated 21 October 2024
biafra ahanonu