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

other entires to explore:

sublime text
16 august 2012 | programming

When coding, writing up blog post, or doing any other task, I generally have used Notepad++. It is a great program that au[...]tomatically detects, based on the extension, the type of code you are writing and parses the file accordingly. It is light and gets the job done, but it always felt like it could be taken to the next level. Enter Sublime Text 2, a program that seems to have everything I am looking for in a text editor and then some.

from the archives: declaration of independence, internet edition
11 july 2013 | america

A revised Declaration of Independence I did awhile ago (i.e. high school) for a writing class. It is slightly a mockery of the style of wri[...]ting sometimes used back then, e.g. finding unnecessarily complicated ways of saying a simple concept; long, ponderous sentences; and an abuse of the Capital.

the nobel prize browser
12 october 2012 | science

Made a small app that allows browsing of Nobel Laureates. Also provides link to their Wikipedia and Pubmed. Might expand to include picture[...]s or some publications. Enjoy!

bio42: notes
12 may 2013 | teaching

While teaching bio42 (cell biology and animal physiology) I created weekly notes to help students in my section study and focus on the impo[...]rtant materials presented in the class. I built off of the latex boilerplate that I have been improving over time to create weekly notes. This highlights why I love LaTeX so much, especially for larger projects that are heavily linked—it allows easy annotation, indexing, creation of new document styles, and other related processes rapidly and consistently. Plus, separating content and style is always a plus and images stay uncoupled from a propriety source (e.g. Word files).

I really love the resulting notes and student feedback was quite positive. I thought sharing them might be useful for others in the future. The source latex files and raw images can be sent upon request (I'm considering making a Github repository in the future). I'll briefly talk about the document below and certain decisions that were made to get it to its current state.

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