Search code examples
rdatatablekablekableextra

Table cell condition w/ Kable in R


I try to color the cells (data_a) if it matches to the data_b with kable, I saw the ifelse function in cell_spec but I didn't succeed.

data_a <- data.table("01:05", "01:05", "01:16", "00:33", "00:52")
data_b <- data.table("00:02", "01:05", "02:30")

kable(data_a, row.names = FALSE, format = "html") %>%
      kable_styling(full_width = F, position = "center")

Thanks


Solution

  • Try it like this:

    library(data.table)
    data_a <- data.table(a =c("01:05", "01:05", "01:16", "00:33", "00:52"))
    data_b <- data.table(b =c("00:02", "01:05", "02:30"))
    library(kableExtra)
    
    data_a %>%
      mutate(a = cell_spec(a, "html", color = ifelse(a %in% data_b$b, "green", "red"))) %>%
      kable(format = "html", escape = F) %>%
      kable_styling("striped", full_width = F)
    

    enter image description here