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)
```
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.