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.

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>A minimal knitr example in HTML</title>
  5. </head>
  6. <body>
  7. <!--begin.rcode
  8. knitr::opts_chunk$set(fig.width=5, fig.height=5)
  9. end.rcode-->
  10. <p>This is a minimal example that shows
  11. how <strong>knitr</strong> works with pure HTML
  12. pages.</p>
  13. <p>Boring stuff as usual:</p>
  14. <!--begin.rcode
  15. # a simple calculator
  16. 1 + 1
  17. # boring random numbers
  18. set.seed(123)
  19. rnorm(5)
  20. end.rcode-->
  21. <p>We can also produce plots (centered by the
  22. option <code>fig.align='center'</code>):</p>
  23. <!--begin.rcode cars-scatter, fig.align='center'
  24. plot(mpg ~ hp, data = mtcars)
  25. end.rcode-->
  26. <p>Errors, messages and warnings can be put into
  27. <code>div</code>s with different <code>class</code>es:</p>
  28. <!--begin.rcode
  29. sqrt(-1) # warning
  30. message('knitr says hello to HTML!')
  31. 1 + 'a' # mission impossible
  32. end.rcode-->
  33. <p>Well, everything seems to be working. Let's ask R what is
  34. the value of &pi;? Of course it is <!--rinline pi -->.</p>
  35. </body>
  36. </html>