1

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.

2
  • Perhaps \Sexpr{pg} Commented Aug 15, 2022 at 23:18
  • Thank you @IRTFM appreciate your help. I am using R Markdown instead of Sweave. But I was able to solve it. Commented Aug 16, 2022 at 2:59

2 Answers 2

2

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}
Sign up to request clarification or add additional context in comments.

Comments

1

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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.