28.8 Including R Commands

20200602 We can include R commands within the knitr (Xie 2023) document and have the commands automatically run when we compile the PDF. The output from the R commands will be displayed together with the R commands themselves.

To include R commands we surround the commands with special markers to create code blocks. The code blocks begin with double less than symbols (or angle brackets <<) starting in column one and end with double greater than symbols (>>) followed immediately by an equals (=). The code block is then terminated by a line containing a single `at'' symbol (@`) starting in column one.

<<>>=
... R code ...
@

Between the angle brackets we place instructions to tell knitr (Xie 2023) what to do with the R commands. We can tell it to simply echo the commands, but not to evaluate them, or to evaluate the commands without echoing them, and so on. Whilst it is optional it is good practice to provide a label for each block of R code. This is the first element between the angle brackets. A simple example of the beginning of a typical code block is:

<<my_label, eval=TRUE, echo=FALSE>>=

The label here is my_label and we ask knitr (Xie 2023) to evaluate the R commands and thus to also show the output of those commands (this is the default). We do not echo the R commands so that the actual commands themselves will not appear in the resulting document (the default is to echo the commands). Whilst we develop our narrative we will include all of the code chunks and the output into the generated PDF report but once we are ready to produce our final report we might turn the echoing of the R code off.

References

———. 2023. Knitr: A General-Purpose Package for Dynamic Report Generation in r. https://yihui.org/knitr/.


Your donation will support ongoing availability and give you access to the PDF version of this book. Desktop Survival Guides include Data Science, GNU/Linux, and MLHub. Books available on Amazon include Data Mining with Rattle and Essentials of Data Science. Popular open source software includes rattle, wajig, and mlhub. Hosted by Togaware, a pioneer of free and open source software since 1984. Copyright © 1995-2022 Graham.Williams@togaware.com Creative Commons Attribution-ShareAlike 4.0