简体   繁体   中英

Rendering Table with conditional color in latex as a pdf document with rownames = TRUE (rmarkdown, kable and kableExtra )

I am attempting to output a latex table using r markdown, kable and kableExtra. When i use the option row.names=FALSE instead of row.names=TRUE the latex code generates \\vphantom code which produce an error to create the pdf . It seems the problem is linked to the row_spec option.

Here is Rmarkdown code (.Rmd File):

---
title: "Test"
output:
pdf_document: 
fig_caption: true
keep_tex: true
---

{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)


{r}
library(knitr)
library(kableExtra)

temp <- mtcars[1:5,1:5]

kable(temp, format = "latex", booktabs = F,row.names=F)  %>%
kable_styling(position = "center") %>%
row_spec(1, bold = T, background = "red")

The error is :

! Forbidden control sequence found while scanning use of \\check@nocorr@. \\par l.105 ...color{red} \\textbf{21.0 &\\vphantom{1} 6} & \\textbf{160} & \\textbf{...

Do you have any issue of what is happening ?

This is caused by the duplicated rows in the dataframe, as both rows 1 and 2 are the same.

Reviewing the code for row_spec_latex , when kableExtra is used against a kable table, it checks for duplicated rows. If it finds one, it inserts the vphantom argument within the fix_duplicated_rows_latex internal function. This vphantom insertion is then messing up the formatting of the textbf function.

This seems like a slight bug, so it may be worth reporting it as an issue in kableExtra: https://github.com/haozhu233/kableExtra . I am sure that the vphantom is added for a good reason though, but doubt this was an intended consequence.

Supporting code:

---
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)

library(knitr)
library(kableExtra)
temp <- mtcars[1:5,1:5]
```

```{r}
# Keeping the row names (means all rows are unique)
kable(temp, format = "latex", booktabs = F)  %>%
  kable_styling(position = "center") %>%
  row_spec(1, bold = T, color = "red")
```

```{r}
# Highlighting second row (which doesn't have the vphantom statement)
kable(temp, format = "latex", booktabs = F, row.names=F)  %>%
  kable_styling(position = "center") %>%
  row_spec(2, bold = T, color = "red")
```

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM