Writing html from R using knitr

Perhaps I lack the obvious, but I struggled to find an example for the following: I would like to write reports about my analysis in R in an html file using the knitr package. I found the stitch() function, however it would be nice to have more control over which results and graphs are written in html and which are not. Basically, I would like to be able to code the following:

 # some dummy code library(ggplot) data <- read.table('/Users/mydata', header=TRUE) model <- lm(Y~X*Y, data) # write this result to html: summary(model) 
+7
source share
2 answers

I think I do not understand what you are missing, but here are the minimum examples that I have prepared. To run this

 library(knitr) knit("r-report.html") 

And an example.

 <HTML> <HEAD> <TITLE>Analyzing Diamonds!</TITLE> </HEAD> <BODY> <H1>Diamonds are everywhere!</H1> <!--begin.rcode echo=FALSE ## Load libraries, but do not show this library(ggplot2) library(plyr) testData <- rnorm(1) end.rcode--> This is an analysis of diamonds, load the data.<p> <!--begin.rcode echo=TRUE, fig.keep="all" # Load the data data(diamonds) # Preview head(diamonds) end.rcode--> Generate a figure, don't show code <p> <!--begin.rcode echo=FALSE, fig.align="center", dev="png" # This code is not shown, but figure will output qplot(diamonds$color, fill=diamonds$color) + opts(title="A plot title") end.rcode--> Show some code, don't output the figure<p> <!--begin.rcode echo=TRUE, fig.keep="none" # Show the code for this one, but don't write out the figure ggplot(diamonds, aes(carat, price, colour=cut)) + geom_point(aes(alpha=0.9)) end.rcode--> And the value testData: <!--rinline testData --> inside a text block. </BODY> </HTML> 
+7
source

Writing HTML inside R is much more time-consuming in my eyes than writing a template and knit() it (@ already gave a decent example). The code will be pretty ugly, and you will see many β€œcats” jumping around. You can get something like this:

 sink('test.html') # redirect output to test.html cat('<h1>First level header</h1>\n') cat('<pre>') summary(mtcars) cat('</pre>\n') sink() browseURL('test.html') 

Anyway, there is another R2HTML package that might be more appropriate in this case.

+6
source

All Articles