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

comments

comments powered by Disqus

other entires to explore:

bash scripting: youtube downloading macro
17 may 2013 | programming

<p> Once again, the command line is the root of all that is good in the world. This time, it has helped improve on a long[...]-standing issue for me: what is the easiest way to get a copy of all the <a href='http://www.youtube.com/playlist?list=PLmku2swCXQpqWAZSscjV4h9bcLennVcif' target='_blank'>luscious melodies</a> i hear on youtube? Courtesy of <a href='http://rg3.github.io/youtube-dl/' target='_blank'>youtube-dl</a>, a nifty little command line utility, this problem has been solved. However, every once in awhile it throws errors and i wanted a wrapper bash script to take care of this and some other processing. I'll briefly go over the code. </p>

¿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 power of myth
11 august 2014 | books

Recently finished The Power of Myth, which covers interviews with Joseph Campbell about myths, and was greatly disappointed. I'll [...]briefly outline why in this review.

interstellar review: was this the final cut?
17 december 2014 | movies

A review of Christopher Nolan's latest movie Interstellar. To put it briefly, rarely has a movie so vastly deviated from my expect[...]ations going in. And not in a good way.

©2006-2017 | biafra ahanonu | updated 19 june 2017
biafra ahanonu