7.15 For hardcore HTML users (*)
In Section 6.12, we mentioned that if you feel the constraint of Markdown (due to its simplicity) is too strong, you can embed code chunks in a pure LaTeX document instead of Markdown. Similarly, if you are familiar and comfortable with writing raw HTML code, you can intermingle code chunks with HTML, too. Such documents have the conventional filename extension .Rhtml
.
In an Rhtml
document, code chunks are embedded between <!--begin.rcode
and end.rcode-->
, and inline R expressions are embedded in <!--rinline -->
. Below is a full Rhtml
example. You can save it to a file named test.Rhtml
, and use knitr::knit("test.Rhtml")
to compile it. The output will be an HTML (.html
) file. In RStudio, you can also hit the Knit
button on the toolbar to compile the document.
<!DOCTYPE html>
<html>
<head>
<title>A minimal knitr example in HTML</title>
</head>
<body>
<!--begin.rcode
knitr::opts_chunk$set(fig.width=5, fig.height=5)
end.rcode-->
<p>This is a minimal example that shows
<strong>knitr</strong> works with pure HTML
how </p>
pages.
<p>Boring stuff as usual:</p>
<!--begin.rcode
# a simple calculator
1 + 1
# boring random numbers
set.seed(123)
rnorm(5)
end.rcode-->
<p>We can also produce plots (centered by the
<code>fig.align='center'</code>):</p>
option
<!--begin.rcode cars-scatter, fig.align='center'
plot(mpg ~ hp, data = mtcars)
end.rcode-->
<p>Errors, messages and warnings can be put into
<code>div</code>s with different <code>class</code>es:</p>
<!--begin.rcode
sqrt(-1) # warning
message('knitr says hello to HTML!')
1 + 'a' # mission impossible
end.rcode-->
<p>Well, everything seems to be working. Let's ask R what is
π? Of course it is <!--rinline pi -->.</p>
the value of
</body>
</html>