I am creating an R-Markdown (Quarto) document for bean aggregation. I have a table within the document and I would like one of the columns (Progress) to have conditional highlighting depending on the cell value (RED if less than 30, GREEN if greater than 70, ORANGE otherwise).
The R-Markdown code is as below (I don't know how to reprex R-Markdown code):
---
title: "delete later"
author: "Tumaini"
format: pdf
editor: visual
---
## Aggregated beans stock
The intention is that the **progress column** is color-coded depending on the value of the cell. It should be **red** if less than 30%, orange between 30% and 70% and green if above 70%
```{r, include=FALSE}
library(tidyverse)
beans_stock = tibble::tribble(
~`Data Entry`, ~District, ~Ward, ~AMCOS, ~`Bean Stock (MT)`, ~`Target (MT)`, ~Progress,
"2022-03-30", "Kasulu", "Nyakitonto", "Nyakitonto", 94.3, 330L, 29L,
"2022-03-29", "Kasulu", "Nyachenda", "Twikome", 63.3, 202L, 31L,
"2022-03-29", "Kibondo", "Kitahana", "Kitahana", 48.3, 88L, 55L,
"2022-03-29", "Kasulu", "Nyachenda", "Motomoto", 44.8, 152L, 29L,
"2022-03-29", "Kasulu", "Kitagata", "Ubhumwe", 37.6, 123L, 31L,
"2022-03-30", "Kakonko", "Kiziguzigu", "Kiziguzigu", 34.4, 410L, 8L,
"2022-03-29", "Kibondo", "Kibondo-Mjini", "Kibondo-Mjini", 17.3, 140L, 12L,
"2022-03-26", "Kibondo", "Kitahana", "Ruti", 6.9, 210L, 3L,
"2022-03-29", "Kibondo", "Bunyambo", "Kibondo-Bunyambo", 4, 140L, 3L,
"2022-03-17", "Kibondo", "Kitahana", "Ruti", 0.6, 210L, 0L
)
```
```{r}
beans_stock %>%
mutate(
Progress = kableExtra::cell_spec(
Progress, background = ifelse(Progress > 70,"green",
ifelse(Progress < 30,"red","orange")))
) %>%
kableExtra::kable(escape = FALSE,format = "latex") %>%
kableExtra::kable_styling("striped", full_width = T)
```
However this is not working, can anyone point to what I might be doing wrong? The intention is to render to PDF.
CodePudding user response:
If you change from background
to color
as the argument in cell_spec()
your code works as expected.
If you want a colored background, you need to remove the last line of code kableExtra::kable_styling("striped", full_width = T)
.
If you want full width, you need to adjust latex options in kable_styling
:
beans_stock %>%
mutate(
Progress = kableExtra::cell_spec(
Progress, background = ifelse(Progress > 70,"green",
ifelse(Progress < 30,"red","orange")))
) %>%
kableExtra::kable(escape = FALSE,format = "latex", booktabs = T) %>%
kableExtra::kable_styling(latex_options="scale_down")