Home > Net >  Rmarkdown: Paragraph ended before \Gin@ii was complete
Rmarkdown: Paragraph ended before \Gin@ii was complete

Time:12-08

I am getting the following error

! Paragraph ended before \Gin@ii was complete.
<to be read again> 
\par 
l.398 

when trying to knit into pdf the following Rmarkdown in Rstudio, which involves defining a variant of \includegraphics.

---
output:
  pdf_document: 
    latex_engine: lualatex
header-include:
  - usepackage{graphicx}
---

\newcommand\IG[1]{\includegraphics[width = \textwidth]{#1}}

\IG{test.png}

Weirdly, the tex output does compile correctly when I execute it through lulatex outside of Rstudio (yes, I do have to use lualatex here).

The error seems to be related to https://tex.stackexchange.com/questions/37650/paragraph-ended-before-giniii-was-complete-while-inserting-image-with-inclu and Rmarkdown Error: "! Paragraph ended before \@fileswith@ptions was complete", but none of the solutions there help and I can't figure out what's going wrong in my case.

Edit: It weirdly seems like the error comes and goes. I get it sometimes, but not others (I just re-ran the above code and it went through this time).

CodePudding user response:

Add the \newcommand to the YAML header, i.e.

---
title: "Test"
output:
  pdf_document: 
    latex_engine: lualatex
    keep_tex: yes
  html_document: default
date: "2022-12-06"
header-include:
  - usepackage{graphicx}
  - \newcommand\IG[1]{\includegraphics[width = \textwidth]{#1}}
---

CodePudding user response:

Here is another workaround I found.

---
output:
  pdf_document: 
    latex_engine: lualatex
    keep_tex: yes
header-include:
  - usepackage{graphicx}
---

```{r}
IG <- function(x){
  return(paste0('\\includegraphics[width = \\textwidth]{', x, '}'))
}
```

`r IG('test.png')`

It's not exactly in the spirit of defining a new LaTex command, but for most (all?) practical purposes, it has the same effect.

In building the R function that outputs the "new command", you just have to be careful to escape the backslash characters with a second backslash.

Although it wasn't something I asked about in my original question, one thing I like about this second solution is it easily allows to make parameters of the "new command" a function of R variables. For example:

---
output:
  pdf_document: 
    latex_engine: lualatex
    keep_tex: yes
header-include:
  - usepackage{graphicx}
---

```{r}
IG <- function(x,y){
  return(paste0('\\includegraphics[width =', y, '\\textwidth]{', x, '}'))
}
```

`r IG('test.png', '0.8')`
  • Related