8

I'm new here, but I've spend few hours on R. I am using a combination of the R package Drake with knitr. However I have an error with the Rmarkdown file. I have a similar structure to the drake example (https://github.com/ropensci/drake), where I load data, make a graph, then a plot and a summary table of my statistical analysis (with the R package kableextra).

Everything works when I select a .tex file, with following lines on my Rmarkdown file

  output: latex_document

  tables: true
  graphics: yes 

and on drake plan

report = rmarkdown::render(
knitr_in("Reports/report.Rmd"),
output_file = "report.tex")

but when I want to have a compiled pdf file as an output with the following lines for rmarkdown header :

output:
  pdf_document: 
    latex_engine: xelatex

tables: true
graphics: yes

and drake

report = rmarkdown::render(
knitr_in("Reports/report.Rmd"),
output_format = "pdf_document",
output_file = "report.pdf")

I received an error message:

`! Undefined control sequence.
<template> ...\hskip 1sp\d@llarbegin \columncolor 
                                                  [HTML]{BBBBBB}\ignorespaces 
l.178 \em{Predictors} & \em
                           {Coefficients} & \em{SE} & \em{P-value} & \em{Coe...

x fail report
Erreur : target report failed.
diagnose(report)$error$message:
  LaTeX failed to compile report.tex. See https://yihui.org/tinytex/r/#debugging for     debugging tips. See report.log for more info.`

So I have searched this error on the net, and go on the website of Yihui. I uninstall all TexLive from my computer, I have uninstall and re-install rmarkdown and tinytex. But it is not working and still have this error. The error occurs just before the table from kableextra package. So I've found other said that adding options(kableExtra.latex.load_packages = FALSE) could help or adding booktabs̀ and makecell on the header of rmarkdown. But it still doesn't work :-/ Any ideas or potential links that I missed?

Update reproductible example

---
title: "Knitr and analysis"
author: "VJ"

output:
  pdf_document: 
    latex_engine: xelatex
    
tables: true
graphics: yes
---

# Example


```{r content, echo = FALSE, include=FALSE}
#tinytex::install_tinytex()
# output:
#   pdf_document: 
#     latex_engine: xelatex
#pdf_document or latex_document
#latex_engine: xelatex
library(glmmTMB)
library(tinytex)
library(drake)
library(tidyverse)
library(pander)
#options(kableExtra.latex.load_packages = FALSE)
library(kableExtra)
options(kableExtra.latex.load_packages = FALSE)
data("iris")
```


```{r analysis qty, echo = FALSE}
    #outputs table from four model 

fitFc = glmmTMB(Sepal.Width ~ Petal.Length +
                      Species, 
                    iris,
                    family = gaussian)



fitFc1 <- as.data.frame(coef(summary(fitFc))$cond) 
varname1 <- c("Intercept", "PL", "Plant 1 - Versicolor", "Plant 2 - Virginica")
fitFc1 <- cbind(varname1,fitFc1)
rownames(fitFc1) <- NULL

m1 <- fitFc1 %>% select(1,2,3,5) %>% 
  rename("Predictors" = 1,
         "Coefficients" = 2,
         "SE" = 3,
         "pvalue" = 4) %>% 
  mutate(pvalue = format.pval(pvalue, eps = .001, digits = 1)) %>% 
  mutate_at(vars(-pvalue, -Predictors), ~round(., 2))


#bold significant pvalue and then create output summary from glmm
m1$pvalue<- cell_spec(m1$pvalue, bold = ifelse(m1$pvalue< 0.05, TRUE, FALSE))

kable(m1, format = "latex", booktabs = T, caption = "Summary of linear model (LMMs).",
      col.names = c("Predictors",
                    "Coefficients",
                    "SE",
                    "P-value"), escape = F) %>% 
  kable_styling(latex_options = c("hold_position")) %>% 
  column_spec(2:4,background = "#BBBBBB") %>% 
  kable_styling() %>%
  add_header_above(c(" " = 1, "LMM1" = 3), bold = T) %>% 
  row_spec(0, bold = FALSE, italic = T)

```

here it is details for my sessionInfo()

Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 18.04.5 LTS

Matrix products: default
BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.7.1
LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.7.1

locale:
 [1] LC_CTYPE=fr_FR.UTF-8       LC_NUMERIC=C               LC_TIME=fr_FR.UTF-8       
 [4] LC_COLLATE=fr_FR.UTF-8     LC_MONETARY=fr_FR.UTF-8    LC_MESSAGES=fr_FR.UTF-8   
 [7] LC_PAPER=fr_FR.UTF-8       LC_NAME=C                  LC_ADDRESS=C              
[10] LC_TELEPHONE=C             LC_MEASUREMENT=fr_FR.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] kableExtra_1.1.0 tinytex_0.25     pander_0.6.3     sjstats_0.18.0   sjPlot_2.8.4    
 [6] glmmTMB_1.0.2.1  lmerTest_3.1-2   lme4_1.1-23      Matrix_1.2-18    ggeffects_0.15.1
[11] effects_4.2-0    carData_3.0-4    cowplot_1.0.0    forcats_0.5.0    stringr_1.4.0   
[16] dplyr_1.0.0      readr_1.3.1      tidyr_1.1.0      tibble_3.0.1     ggplot2_3.3.2   
[21] tidyverse_1.3.0  drake_7.12.4     purrr_0.3.4     

loaded via a namespace (and not attached):
 [1] minqa_1.2.4         colorspace_1.4-1    ellipsis_0.3.1      sjlabelled_1.1.6   
 [5] estimability_1.3    parameters_0.8.2    fs_1.4.2            rstudioapi_0.11    
 [9] farver_2.0.3        fansi_0.4.1         mvtnorm_1.1-1       lubridate_1.7.9    
[13] xml2_1.3.2          splines_4.0.2       knitr_1.29          sjmisc_2.8.5       
[17] jsonlite_1.7.0      nloptr_1.2.2.2      broom_0.5.6         dbplyr_1.4.4       
[21] effectsize_0.3.2    compiler_4.0.2      httr_1.4.1          emmeans_1.4.8      
[25] backports_1.1.8     assertthat_0.2.1    survey_4.0          cli_2.0.2          
[29] htmltools_0.5.0     prettyunits_1.1.1   tools_4.0.2         igraph_1.2.5       
[33] coda_0.19-3         gtable_0.3.0        glue_1.4.1          Rcpp_1.0.5         
[37] cellranger_1.1.0    vctrs_0.3.1         nlme_3.1-147        insight_0.9.0      
[41] xfun_0.16           rvest_0.3.5         lifecycle_0.2.0     statmod_1.4.34     
[45] MASS_7.3-51.6       scales_1.1.1        hms_0.5.3           parallel_4.0.2     
[49] TMB_1.7.18          RColorBrewer_1.1-2  yaml_2.2.1          stringi_1.4.6      
[53] bayestestR_0.7.2    filelock_1.0.2      boot_1.3-25         storr_1.2.1        
[57] rlang_0.4.7         pkgconfig_2.0.3     evaluate_0.14       lattice_0.20-41    
[61] labeling_0.3        tidyselect_1.1.0    magrittr_1.5        R6_2.4.1           
[65] generics_0.0.2      base64url_1.4       txtq_0.2.3          DBI_1.1.0          
[69] mgcv_1.8-31         pillar_1.4.4        haven_2.3.1         withr_2.2.0        
[73] survival_3.2-3      nnet_7.3-14         performance_0.4.8   modelr_0.1.8       
[77] crayon_1.3.4        utf8_1.1.4          rmarkdown_2.3.3     progress_1.2.2     
[81] grid_4.0.2          readxl_1.3.1        blob_1.2.1          reprex_0.3.0       
[85] digest_0.6.25       webshot_0.5.2       xtable_1.8-4        numDeriv_2016.8-1.1
[89] munsell_0.5.0       viridisLite_0.3.0   mitools_2.4```        
Vale
  • 81
  • 1
  • 4
  • Do you get the same error if you run the report outside `drake`? – landau Aug 25 '20 at 15:04
  • Also, it would help to see the full `Reports/report.Rmd` file you are using. Related: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – landau Aug 25 '20 at 15:05
  • I've updated my request. Do not know why, but I can not add the "chunk" code, which is just after "#example" till the end – Vale Aug 25 '20 at 15:57
  • Thanks, that helps narrow it down. I also formatted the R Markdown source (indent 4 spaces) and removed the `drake-r-package` tag since the error appears to not come from `drake`. – landau Aug 25 '20 at 16:30
  • The report compiles fine on my end, so I'm not sure I'm the best person to help with the LaTeX issues, but I think it would help to provide others with your system info: OS, `sessionInfo()`, versions of LaTeX, etc. You might also see what happens if you do not manually set a LaTeX engine. The report still ran okay on my end when I removed `xelatex`. – landau Aug 25 '20 at 16:33
  • I'm using Ubuntu 18.04.5 LTS. I still have this error. I do not know why, but it seems that sometimes it could work (meaning that I could have a compiled pdf if I run directly the Rmd file, even if the error is displayed) but not when I run it with the drake package. – Vale Aug 27 '20 at 08:30
  • And as I said, and found on the git of knitr package, they said that it is better to use directly tinytex. Here it is another example, and it seems not new. They said that he can only produce tex file; https://github.com/rstudio/rmarkdown/issues/1523 – Vale Aug 27 '20 at 09:00
  • I've tested with my personal laptop, and I still have this error. An interesting point is that it seems to work when I run directly the Rmd file (I have the compiled pdf with all modifications, and I obtain a pdf file), but not when I am using the make function from the drake package, I still have this error. Any thoughts? I think that the mistake is maybe during this function ```report = rmarkdown::render``` – Vale Aug 27 '20 at 20:18
  • I tried again, and I was able to reproduce it with `rmarkdown::render()` in the R console outside `drake`. The culprit seems to be `column_spec(2:4,background = "#BBBBBB")`. When I comment it out, the pdf renders fine. – landau Aug 27 '20 at 21:19
  • Yes me too, as I said, it works when I run only the rmd file (with or without deleted lines) but not with the make function from drake. I still have an error and no pdf at the end ```! Extra alignment tab has been changed to \cr. \endtemplate x fail report Erreur : target report failed. diagnose(report)$error$message: LaTeX failed to compile report.tex. See https://yihui.org/tinytex/r/#debugging for debugging tips. See report.log for more info.``` – Vale Aug 28 '20 at 08:54
  • When you run outside drake, are you using rmarkdown::render() or the knit button in RStudio? – landau Aug 28 '20 at 11:45
  • I cannot reproduce that new error using either `drake` or `rmarkdown::render()` on its own. If you can reproduce using `rmarkdown::render()` only, please consider reposting as a purely LaTeX/R Markdown question. – landau Aug 28 '20 at 12:25
  • Just realized I was encountering https://github.com/glmmTMB/glmmTMB/issues/615. After reinstalling `glmmTMB`, I can reproduce the "Extra alignment tab has been changed to \cr" error with a simple `rmarkdown::render("report.Rmd")` in the R console outside `drake`. I recommend reposting as an R/LaTeX question. – landau Aug 28 '20 at 12:39
  • Ok, so it's working when I click on the knit button but not with ```rmarkdown::render```. Do you think that it is because I've made a mistake in the function rmarkdown? (I am using the same as the initial post with the rmd file inside a folder) – Vale Aug 28 '20 at 12:54
  • I’m not sure. Please see my answer. – landau Aug 28 '20 at 13:05

4 Answers4

3

When I get questions like these, the first thing I try to do is reproduce the error in the R console outside drake. Often, these kinds of errors are not due to drake itself but instead due to the fact that drake requires you to write extra custom code. In this case, the report runs with the Knit button in the RStudio IDE, but not with rmarkdown::render("report.Rmd"). This leads me to believe the problem is somewhere in the report, our TeX configurations, tinytex, kable, kableExtra, or pander. I suggest reposting this question as an R Markdown/LaTeX issue instead of a drake issue so you can get the right people to help you.

To elaborate on what I tried:

  1. When I press the Knit button in the RStudio IDE, the report runs normally and produced a reasonable-looking report.pdf file.
  2. When I run the report using rmarkdown::render("report.Rmd") in the R console outside drake, I get "! Undefined control sequence. <template> ...\hskip 1sp\d@llarbegin \columncolor [HTML]{BBBBBB}\ignorespaces".
  3. When I comment out column_spec(2:4,background = "#BBBBBB") and run rmarkdown::render("report.Rmd") again, I get a new error: "! Extra alignment tab has been changed to \cr. <recently read> \endtemplate.

Another thing: the R community is trying to retire the iris dataset because of its connection to eugenics research: https://armchairecology.blog/iris-dataset/, https://www.garrickadenbuie.com/blog/lets-move-on-from-iris/. Please avoid it whenever possible. A great drop-in replacement is the penguins dataset: https://github.com/allisonhorst/palmerpenguins. Here is a version of your report that uses penguins instead of iris.

---
title: "Knitr and analysis"
author: "VJ"
output:
  pdf_document: 
    latex_engine: xelatex
tables: true
graphics: yes
---

# Example

```{r content, echo = FALSE, include=FALSE}
library(glmmTMB)
library(tinytex)
library(drake)
library(tidyverse)
library(pander)
library(kableExtra)
options(kableExtra.latex.load_packages = FALSE)
library(palmerpenguins)
```

```{r analysis qty, echo = FALSE}
fitFc <- glmmTMB(bill_length_mm ~ bill_depth_mm + species, penguins, family = gaussian)
fitFc1 <- as.data.frame(coef(summary(fitFc))$cond) 
fitFc1$variable <- rownames(fitFc1)
rownames(fitFc1) <- NULL
m1 <- fitFc1 %>%
  select(variable, everything()) %>%
  select(1,2,3,5) %>% 
  rename("Predictors" = 1, "Coefficients" = 2, "SE" = 3, "pvalue" = 4) %>% 
  mutate(pvalue = format.pval(pvalue, eps = .001, digits = 1)) %>% 
  mutate_at(vars(-pvalue, -Predictors), ~round(., 2))
m1$pvalue <- cell_spec(m1$pvalue, bold = ifelse(m1$pvalue< 0.05, TRUE, FALSE))
kable(
  m1,
  format = "latex",
  booktabs = T,
  caption = "Summary of linear model (LMMs).",
  col.names = c("Predictors", "Coefficients", "SE", "P-value"), escape = F) %>% 
  kable_styling(latex_options = c("hold_position")) %>% 
  column_spec(2:4,background = "#BBBBBB") %>% 
  kable_styling() %>%
  add_header_above(c(" " = 1, "LMM1" = 3), bold = T) %>% 
  row_spec(0, bold = FALSE, italic = T)
```
landau
  • 5,636
  • 1
  • 22
  • 50
  • 1
    Thank you for your help. When we deleted the table from kableextra it works, so the error might come to kableextra. Maybe I forgot something in the script? – Vale Aug 28 '20 at 18:50
  • 1
    Would you move the discussion to an issue on the kableextra GitHub page or a new StackOverflow issue about kableextra? We now have a smaller reproducible example, and we have established that drake is not part of the problem, so I think follow-up should continue in a different post. You’ll get help from people who know kableextra better than I do. – landau Aug 28 '20 at 22:50
0

So, I've put my request on GitHub and finally solved it thanks to Hao Zhu!

What I've done:

  • delete options(kableExtra.latex.load_packages = FALSE)
  • update the kableExtra package v1.2 with devtools::install_github("haozhu233/kableExtra")
  • restart my R session
  • run
report = rmarkdown::render(
    #envir = new.env(),  
    knitr_in("Reports/report.Rmd"),
    output_format = "pdf_document",
    output_file = "report.pdf") 

Note that it should work with or without envir = new.env() if you update the package

see here for original answer: https://github.com/haozhu233/kableExtra/issues/501

Vale
  • 81
  • 1
  • 4
0

I have a similar ("LaTeX failed to compile .tex" with "! Undefined control sequence") problem to knit into PDF (although not for .docx), but not involving kableextra, so, I think it can be a good idea to share how it was resolved in my case...

I had:

   knitr::opts_chunk$set(
        echo = FALSE,
        message = FALSE,
        collapse=FALSE,
        warning = FALSE,
        results='asis'
    )

attempting to include some subtitles inside loops... None of the solutions listed in several places like here or here, like updating packages or re-installing TinyTeX were working...

I noticed in the error message for your case there was a 'ignore spaces', for another question, '|', and for me something like '\n'... So, I realized it possibly has something with formatting and new line definitions...

So, after some attempts, I found the results='asis' was causing all the trouble... Deleting it solved.

hamagust
  • 728
  • 2
  • 10
  • 28
0

As with @hamagust above, I was also experiencing the "LaTeX failed to compile .tex" with "! Undefined control sequence" error in Rmarkdown, but not involving kable or kableextra.

After much pain, I found the issue was to do with using the newline character "\n" within the body of the report (outside code chunks). Instead, following the advice offered here and using "\linebreak" instead, and including the 'empty' character (ALT+255) to prevent markdown complaining that there is 'no line to end'.

This is notable because, inside a loop within a code chunk, and when wrapped in cat(), the newline character \n seems to work just fine. ¯_(ツ)_/¯