I have an existing LaTex-Document. I have conducted a Data Analysis in R and created a .Rmd-File for it. I have received the corresponding .tex-file via:
knitr::knit("test.Rmd")
markdown::pandoc_convert("test.md", to = "latex", output = "R_code.tex")
Now, I want to integrate the R_code.tex-File into my existing LaTex document:
\documentclass{article}
\usepackage{
float,
graphicx,
mathtools,
microtype,
paralist,
xcolor,
framed
}
\begin{document}
\definecolor{shadecolor}{gray}{0.9}
Hello World.
\input{R_code}
\end{document}
However, if I now run the LaTex script, I get error after error coming from the R_code.tex-file. There are undefined environments (such as shaded
or highlighting
and lots of undefined control sequences such as \NormalTok
or \OtherTok
.
How can I make sure the .tex-File from R/Markdown integrates nicely into my existing LaTex File? Am I just missing additional packages or some commands in the R-script? Or is there another, simpler way?
Code for Rmd-File:
---
title: "test"
output: html_document
date: "2024-09-08"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
Lorem Ipsum...
```{r cars}
summary(cars)
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
You shouldn't use output: html_document
, use output: latex_fragment
.
Then run rmarkdown::render("R_code.Rmd")
.
This will produce R_code.tex
which should work with your \input{R_code}
statement in the LaTeX document.
Edited to add:
I forgot to mention that you will need to add things to the preamble if the main document isn't being produced by RMarkdown as well. To do that, run your add-in as latex_document
first, and copy about 100 lines from the preamble to the preamble of your main document. These lines look like this:
\usepackage{amsmath,amssymb}
\usepackage{iftex}
... skipping most of the lines ...
\hypersetup{
pdftitle={test},
hidelinks,
pdfcreator={LaTeX via pandoc}}
I pasted them into the main test document just after the \usepackage{ ... }
block that was already there, and after changing the insert back to latex_fragment
and redoing it, the whole thing worked.
By the way, the patchDVI
package provides support for complicated projects doing things like this. You can run one command on any file and it will produce the PDF for the whole document.