7

Maybe I am missing the obvious, but I have been struggling with finding an example for the following: I would like to write reports of my analysis in R to a html file using the knitr package. I have found the stitch() function, however it would be nice to have more control about which results & plots are written to html and which are not. In principal 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)
1
  • thanks for the hint. But doesnt this example show how you embed R-code within a html file. I would rather like to create a html file and write content to it WITHIN R. Just like stitch() does, only that I would like to have more flexibility than just write everything to the html file. Commented Apr 28, 2012 at 12:00

2 Answers 2

8

I guess I do not understand exactly what you are lacking, but here is a minimal examples I cooked up. To run this

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

And the 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>
Sign up to request clarification or add additional context in comments.

Comments

6

Writing HTML within R is much more laborious in my eyes than writing a template and knit() it (@dready has given a decent example). The code will be rather ugly, and you will see lots of "cats" jumping around. You may end up with 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 package R2HTML which may be more suitable in this case.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.