LaTeX
- Getting Started with LaTeX
- Overleaf
- LaTeX BasicsToggle Dropdown
- BibTeX BasicsToggle Dropdown
- LaTeX-STEM ApplicationsToggle Dropdown
- Beamer (Presentations)
- knitr (R Code in LaTeX)
- Overleaf Workshops/TutorialsToggle Dropdown
Science and Engineering Librarian
740 North Pleasant Street
Amherst, MA 01003
Overview of knitr
Are you using R to do data analysis and/or create visualizations you plan to report using LaTeX? Good news! You can directly integrate your R code into your LaTeX code, thanks to a software engine called knitr. If you are using Overleaf, there is nothing you need to set up, simply follow the guidelines below to get started.
Chunks
knitr operates using segments of code referred to as "chunks." You can think of chunks as working similarly to environments in LaTeX. Chunks are created using the following code:
<<>>=
R Code Goes Here.
@
Options can be inserted inside the top-line (in between <<
and >>=
) that will affect how the code is reported/executed, as well as how any plots are formatted. The chunk can also be labeled, simply by typing a name without an option. The chunk can then be referenced using the command: \ref{fig:chunkname}
.See the table below for some common chunk options and their effects.
Option | Effect | Arguments |
---|---|---|
|
Display Code in Resulting Output PDF |
|
include |
Display Whole Chunk (Code and Results) in Resulting Output PDF |
|
eval |
Execute Code in the Chunk |
|
fig.width |
Width of Plot Created | X = Plot will have a width of X inches |
fig.height |
Height of Plot Created | X = Plot will have a height of X inches |
fig.pos |
Position in Output PDF for Plot Created |
|
fig.cap |
Caption for Plot Created | "Example Caption Text" = Example Caption Text |
fig.align |
Alignment in Output PDF for Plot Created |
|
In-Line R Code
You may want to reference small pieces of information produced by your embedded R code Chunks (e.g. a p-value from an ANOVA) when writing in your LaTeX document. Rather than copying a value from the R output and pasting it in your LaTeX source code, you can use the command \Sexpr{R Code}
to integrate the R code (and its output) directly into your writing. This way, should the referenced output change (e.g. you update the dataset, affecting the statistical analysis) your references to the output will update automatically.
Example Output
Below is the output PDF created in LaTeX, using knitr to embed R code. The R code embedded in the LaTeX code allows the user to produce a plot (in this example, using ggplot) directly in the output document. The embedded R code is also used to perform the ANOVA and Tukey's HSD referenced in the text. The p-values referenced in the text are generated by using the \Sexpr{R Code}
command described above. View the full project on Overleaf here.
- Last Updated: Jan 2, 2025 2:43 PM
- URL: https://guides.library.umass.edu/LaTeX
- Print Page