Data Science Desktop Survival Guide
by Graham Williams |
|||||
Inline R Code |
20200602 Often we find ourselves wanting to refer to the
results of an R command within the text we are writing rather than
as a separate code chunk. This is easily done using the
\Sexpr{}
command in LaTeX.
To include today's date within the narrative we can type the command
sequence exactly as \Sexpr{Sys.Date()}
. This will
be replaced with 2026-07-20 (assuming that is today). Any
R function can be called in this way. To format the date, for
example, we can use R's base::format() function to
specify how the date is displayed, so to produce Wednesday, 20
July 2026 we would use \Sexpr{Sys.Date() %>% format(format="%A, %e %B %Y")}
.
We typically intermix a narrative of our dataset with output from R
to support and illustrate the discussion. In the following sentence we
do this showing first the output from the R command and then the
actual R command we included in the source document. For example,
the weatherAUS dataset from rattle has
176,747 (i.e.,
\Sexpr{comma(nrow(weatherAUS))}
) observations including
observations of the following 4 of the 24 (i.e.,
\Sexpr{ncol(weatherAUS)}
) available variables:
MinTemp, MaxTemp, Rainfall, Evaporation.
That list was generated using
\Sexpr{names(weatherAUS)[3:6] %>% paste(collapse=", ")}
.
LaTeX treats some characters specially and we need to be careful to
escape such characters. For example, the underscore “_
” is
used to introduce a subscript in LaTeX. It needs to be escaped if
we really want an underscore to be included in the compiled PDF
document. If not LaTeX will likely complain. As an example we might
list one of the variable names from the weatherAUS dataset with
an underscore in its name: RISK_MM
(\Sexpr{names(weatherAUS)[23]}
). We will see an error
like:
KnitR.tex:230: Missing $ inserted. KnitR.tex:230: leading text: ...an underscore in its name: RISK_ KnitR.tex:232: Missing $ inserted. |
Hmisc provides Hmisc::latexTranslate() to assist
here. It was used above to print the variable name:
\Sexpr{latexTranslate(names(weatherAUS)[23])}
. There
are other support functions in Hmisc that are useful
when working with knitr and LaTeX—see
library(help=Hmisc)
for further information.