Data Science Desktop Survival Guide
by Graham Williams
Including R Commands
20200602 We can include R commands within the knitr 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.
Between the angle brackets we place instructions to tell knitr 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:
The label here is my_label and we ask knitr 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.