Kable Tables with change Background color

Hello Team.

I want to develop a table that can show progress "red" indicate poor performance , "yellow" improved performance and "green"" good performance. I am able to include two color, to include a third color I am failing. is there a way I can do it in using kable package.

the following is the code I am using.

Nation_tabel2%>%
  mutate(coverage=cell_spec(coverage,
        background= ifelse(coverage<50, "red", "green")))%>%
     knitr::kable(format = "html", escape = FALSE, booktabs= T, linesep= "")%>%
   kable_styling(bootstrap_options="condensed", full_width=FALSE, position="center", latex_options="scale_down", 
                 font_size=20, font(color="black"))%>%
  column_spec(1, border_right=T)%>%
  column_spec(10, border_right=T)%>%
  row_spec(11, bold=T, hline_after=T)%>%
  row_spec(1:11, color="black")%>%
  column_spec(1, width="10em")

here is the data I am using

structure(list(district = c("blantyre", "dowa", "kasungu", "lilongwe", 
"machinga", "mangochi", "mzimba north", "mzimba south", "nsanje", 
"thyolo", "Total"), doses_available = c(19860, 16600, 11045, 
19465, 32990, 12650, 21815, 24420, 10610, 12990, 182445), HW_total = c(0, 
0, 0, 0, 0, 0, 0, 0, 0, 0, 0), sw_total = c(1018, 0, 0, 0, 0, 
0, 0, 0, 0, 1418, 2436), comb_total = c(171, 0, 0, 0, 254, 0, 
0, 0, 0, 69, 494), years_18_59 = c(9001, 0, 0, 0, 25911, 0, 0, 
0, 0, 5362, 40274), above_60 = c(235, 0, 0, 0, 612, 0, 0, 0, 
0, 733, 1580), ref_total = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), 
    pri_total = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), total_vacc = c(10425, 
    0, 0, 0, 26777, 0, 0, 0, 0, 7582, 44784), coverage = c(52.5, 
    0, 0, 0, 81.2, 0, 0, 0, 0, 58.4, 24.5)), row.names = c(NA, 
11L), class = c("tabyl", "data.frame"))

I think this does more or less what you want.

suppressMessages(library(data.table)); 
suppressMessages(library(tidyverse))
library(kableExtra)

Nation_tabel2 <- read.csv("nation.csv")

setDT(Nation_tabel2) # convert to data.table format

Nation_tabel2[, coverage := cell_spec(coverage,
        background =  fcase(
                          coverage <= 40, "red",
                          coverage <= 60, "yellow",
                          coverage >= 61, "green"
                          ))]

Nation_tabel2 |> kable(format = "html", escape = FALSE, booktabs= T, linesep= "")%>%
   kable_styling(bootstrap_options="condensed", full_width=FALSE, position="center", latex_options="scale_down", 
                 font_size=20, font(color="black"))%>%
  column_spec(1, border_right=T)%>%
  column_spec(10, border_right=T)%>%
  row_spec(11, bold=T, hline_after=T)%>%
  row_spec(1:11, color="black")%>%
  column_spec(1, width="10em")

Thanks A lot it has worked.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.