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

additional articles to journey through:

week 0 | singapore!
26 may 2012 | singapore

First post about Singapore lays out some of the background surrounding the trip and Singapore itself. This summer is going to be awesome![...]p>

filugori reboot
15 may 2012 | filugori

Several months ago I took a hard look at Filugori: The Long Tale, the story I started in grade school that was meant to be a mash-[...]up of my favorite books and fictional universes. However, it lacked a certain vision. The story was fun, frantic and fanciful, but there was no heart. It lacked cohesion and the universe did not appear to justify its own existence. Why should someone care to read this tale? What would they gain from it? While fleshing out the background of the universe, providing details on the four major epochs that define the story, I came to realize that I wanted to tell a very different tale than originally planned.

justifying hyphens
21 october 2012 | website

Justified text is awesome. Clean lines align well with other elements and it doesn't produce a crazy jagged edge. But without hyphens, prob[...]lems quickly arise. Some lines have super large spaces between words and the end look is quite ugly. There are several solutions: css, server-side, and javascript.

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