Home > Software engineering >  How to run r code within the latex code in Rmarkdown
How to run r code within the latex code in Rmarkdown

Time:08-17

Consider the following code in Rmarkdown, which produces a graph as below:

\begin{figure}
\centering
\captionsetup{skip=0pt}
\includegraphics[width=6cm]{example-image-a}
\caption{A test caption}
\end{figure}

Output:

enter image description here

Now, instead of just using a graph, I would like to create my own plot in Rmarkdown, for example, using this code:

\begin{figure}
\centering
\captionsetup{skip=0pt}
\includegraphics[width=6cm]{plot(mtcars$mpg)}
\caption{A test caption}
\end{figure}

but the following error is produced instead:

! LaTeX Error: File `plot(mtcars$mpg)' not found.

Is there any way to run r codes within latex?

CodePudding user response:

R Markdown doesn't work this way. If you are using RStudio, it is pretty easy. In the R Markdown file, type

plot(mtcars$mpg)

In other words, you need to start your code with three back-ticks and {r}, and stop your code with three back-ticks again. Your R code written this way will produce the plot you require. After that, click on "knit" button, or use rmarkdown::render(your_file_name).

What you have written in the question means you have produced this chart, and saved that chart as a file in your working directory. If you have saved your plot in the working directory, your code will still work. Try it.

CodePudding user response:

you could try plotting to a file device e.g.

png(filename="mtcars_mpg.png")
plot(mtcars$mpg)
dev.off()

then bring the file in with your LaTeX code:

\begin{figure}
\centering
\captionsetup{skip=0pt}
\includegraphics[width=6cm]{mtcars_mpg.png}
\caption{A test caption}
\end{figure}
  • Related