Abbas
Abbas

Reputation: 897

How to run r code within the latex code in Rmarkdown

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?

Upvotes: 0

Views: 626

Answers (2)

Ratey at UWA
Ratey at UWA

Reputation: 46

you could try plotting to a file device in an R code chunk e.g.

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

You can hide this chunk by using include = FALSE in the chunk options.

Then just 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}

Upvotes: 2

Eva
Eva

Reputation: 851

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.

Upvotes: 2

Related Questions