6.8 For hardcore HTML users

In Section 5.8, 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>
  <title>A minimal knitr example in HTML</title>
  knitr::opts_chunk$set(fig.width=5, fig.height=5)

  <p>This is a minimal example that shows
  how <strong>knitr</strong> works with pure HTML

  <p>Boring stuff as usual:</p>

    # a simple calculator
    1 + 1
    # boring random numbers

  <p>We can also produce plots (centered by the
  option <code>fig.align='center'</code>):</p>

<!--begin.rcode cars-scatter, fig.align='center'
    plot(mpg ~ hp, data = mtcars)

  <p>Errors, messages and warnings can be put into
  <code>div</code>s with different <code>class</code>es:</p>

    sqrt(-1)  # warning
    message('knitr says hello to HTML!')
    1 + 'a'  # mission impossible

  <p>Well, everything seems to be working. Let's ask R what is
  the value of &pi;? Of course it is <!--rinline pi -->.</p>