0

I am trying to print a table int a PDF report. In this report, I want to change the format of a cell in a table using cell_spec (together with kable). I created this report using R-Markdown (with latex for the PDF output).

Searched around many other questions before posting, this was the closest, but the accepted answer doesn't work for me: Selecting and colouring single table cells with kableExtra in R markdown cell_spec

Here is the code:

```
title: "Title"
author: "Me"
output:
  pdf_document:
    toc: yes
    fig_caption: yes
header-includes:
     \usepackage{fancyhdr}
     \usepackage{graphicx}
```

```{r setup, include=FALSE}
#options(tinytex.verbose = TRUE)
knitr::opts_chunk$set(
    echo = FALSE,
    message = FALSE,
    warning = FALSE,
    out.width = "100%"
)

#.1. Load libraries
require("pacman")
p_load(tidyverse,reshape, reshape2, ggplot2, knitr, kableExtra, tinytex, scales)
```
I have a table and I would like the cell on the first row, second column to have a green background.
For the example I am using this code:

```{r, escape = FALSE, results='asis'}

col1=c('Expect_Positive', 'Expect_Negative')
Real_Positive = c(10,1)
Real_Negative=c(3,15)

conf_matrix= as.data.frame(cbind(col1, Real_Positive, Real_Negative))

conf_matrix[1,2]=cell_spec(conf_matrix[1,2], format="latex", background = "green")

conf_matrix  %>%
      kable(format = "latex", booktabs = TRUE,
            caption = paste0("Confusion Matrix Example"),
            align = "c") %>%
      kable_styling(latex_options = c("HOLD_position")) %>%
      kable_styling(font_size = 8.5)
 
```

Here is what I get: Table with latex command instead of actual background

As you can see it prints the actual command: \cellcolor{green}{10} instead of giving the background color as I would like.

I have successfully changed background colors in other cases using column_spec and row_spec but in my particular case I really want to be able to change format of a specific cells.

lu-202
  • 121
  • 7

1 Answers1

1

Change your last chunk to (you would have to escape the underscores as an alternative):

```{r, results='asis'}

col1=c('Expect.Positive', 'Expect.Negative')
Real.Positive = c(10,1)
Real.Negative=c(3,15)

conf_matrix= as.data.frame(cbind(col1, Real.Positive, Real.Negative))

conf_matrix[1,2]=cell_spec(conf_matrix[1,2], background = "green", format = "latex")

conf_matrix  %>%
      kable(format = "latex", booktabs = TRUE, escape = FALSE,
            caption = paste0("Confusion Matrix Example"))
```

enter image description here

Julian
  • 6,586
  • 2
  • 9
  • 33