Home > Enterprise >  Inserting predefined R variable inside LaTeX code
Inserting predefined R variable inside LaTeX code

Time:08-16

I was wondering whether it is possible to include variable in LaTeX code when compiling a PDF document in R Markdown. For example, I want to use includegraphics to include an image from an external PDF file.

Normally I use a code similar to:

\begin{figure}
\includegraphics[page=66, viewport = {198 391 452 623}, clip]{book.pdf}
\end{figure}

Now, I want to use variables pg for pages and trim_areas for viewport pt (using inline r).

```{r}
trim_areas <- c(198, 391, 452, 623)
pg <- 66
```

Now I want to use these variables:

\begin{figure}
\includegraphics[page=`r noquote(pg)`, viewport = {`r noquote(trim_areas)`}, clip]{book.pdf}
\end{figure}

But this is not working.

CodePudding user response:

I was able to solve the issue using following code in R Markdown:

\begin{figure}
\includegraphics[page = `r pg`, viewport = {`r trim_areas[1]` `r trim_areas[2]` `r trim_areas[3]` `r trim_areas[4]`}, clip]{book.pdf}
\end{figure}

CodePudding user response:

Instead of indexing trim_areas four times, you can try this

```{r}
trim_areas <- c(198, 391, 452, 623)
pg <- 66

viewport <- knitr::combine_words(trim_areas, and = "", sep = " ")
```

viewport object looks like,

viewport

#> 198 391 452 623

Then simply use this in your latex code,

\begin{figure}
\includegraphics[page = `r pg`, viewport = {`r viewport`}, clip]{book.pdf}
\end{figure}
  • Related