Knitr and ReportingTools

Jessica L. Larson and Gabriel Becker

We can use knitr and ReportingTools together, as shown in this very simple example from our basic vignette.

Here we will create a simple report that integrates ReportingTools report capabilities with knitr.

To build this report, simply call the knit2html function from the knitr package.

my.df <- data.frame(EGID = c("103", "104", "105", "106", "107"),
                    RPKM = c(4, 5, 3, 100, 75),
                    DE = c("Yes", "Yes", "No", "No", "No"))


We now can publish our data frame as table through the use of the knitrHandlers. When using knitrHandlers we must specify the destination location as an argument either to the knitrHandlers constructor function directly or as an additional argument to HTMLReport when knitrHandlers is specified in the handlers argument.

We do not call finish since we will still add output to our knitr report.

instDoc <- file.path("..", "inst", "doc")
htmlRep <- HTMLReport(shortName = "knitrReport", handlers=knitrHandlers,
                      reportDirectory = instDoc)

#publish(my.df, htmlRep)
htmlRep[["mydf"]]<-my.df  ##this line is equivalent to the line above
103 4Yes
104 5Yes
105 3No
107 75No

Thus we are able to include tables generated by ReportingTools based directly within knitr documents.

Now we will try to put in an image:

htmlRep[["pic"]] = xyplot(y~x, data = data.frame(y=rnorm(25), x=rnorm(25)))
##We could also add a picture like this:
y <- rnorm(500)
pic2<-histogram(y, main="Sample of 500 observations from a Normal (0,1)")
publish(pic2, htmlRep)

To build the report, simply call the knit2html function from the knitr package.

As we have seen, using ReportingTools in conjunction with knitr is as easy as selecting a different set of ReportHandlers (in this case those generated by the knitrHandlers constructor function) and ensuring that the location of the final HTML file matches (up to the directory) that specified by the location field of that ReportHandlers object.

This allows us to create rich knitr-based reports and vignettes while leveraging the power of ReportingTools to format and display generated R objects.