28.10 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 r Rfunction(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 dataset from (G. Williams 2024) has
226,868 (i.e.,
\Sexpr{comma(nrow(weatherAUS))}
) observations including
observations of the following 4 of the ncol(weatherAUS)
(i.e.,
\Sexpr{ncol(weatherAUS)}
) available variables:
MinTemp, MaxTemp, Rainfall, Evaporation.
That list was generated using
MinTemp, MaxTemp, Rainfall, Evaporation.
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 dataset with
an underscore in its name: RISK_MM
(RISK_MM). 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.
(Harrell 2024) 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 (Harrell 2024) that are useful
when working with knitr (Xie 2024) and LaTeX—see
library(help=Hmisc)
for further information.
References
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