Search code examples
rlatexr-markdownmarkdown

Inserting predefined R variable inside LaTeX code


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}

I wanted 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
```

And use these variables in LaTeX code:

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

But this is not working and giving me an error.


Solution

  • 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}