Home > Back-end >  How to change colour of specific text-values using kableextra
How to change colour of specific text-values using kableextra

Time:10-05

I am trying to change the color of the text or alternatively have colored backgrounds in some cells of my table by making "positive" green, "negative" red and have "neutral" remain black.

I have searched for a solution but can only find conditional formatting based on numbers. How to I change the color based on the text in my cells?

For reference, this is my code for now:

`Date` <- c("24-02-2022", "04-04-2022", "01-04-2022", "18-05-2022", "28-02-2022", "04-03-2022", "05-03-2022", "08-03-2022", "05-05-2022", "12-05-2022", "25-05-2022")
`Predicted reaction` <- c("Negative", "Negative", "Negative", "Neutral", "Negative", "Positive", "Positive", "Negative", "Positive", "Negative", "Neutral")


df3 <- data_frame(`Date`, `Predicted reaction`)
df3 %>%
 kbl(caption = "Timeline of Events") %>%
 kable_classic(full_width = F, html_font = "Cambria")%>%
 pack_rows("All", 1, 4) %>%
 pack_rows("Spesific", 5, 11)

This results in the following table:

Table 1

CodePudding user response:

Have you tried the ifelse function?

df3 = cell_spec(df3, color = ifelse(df3 = 'Positive', "green","red")))

CodePudding user response:

Is this what you were looking for?

I've changed some of the variables slightly to save a bit of typing.

library(kableExtra)
library(dplyr)

date <- c("24-02-2022", "04-04-2022", "01-04-2022", "18-05-2022", "28-02-2022", "04-03-2022", "05-03-2022", "08-03-2022", "05-05-2022", "12-05-2022", "25-05-2022")
pr <- c("Negative", "Negative", "Negative", "Neutral", "Negative", "Positive", "Positive", "Negative", "Positive", "Negative", "Neutral")


df3 <-
  data.frame(date, pr) |>
  mutate(pr = cell_spec(pr, color = ifelse(pr == "Positive", "green", ifelse(pr == "Negative", "red", "black"))))


df3 |> 
  kable(caption = "Timeline of Events",
        col.names = c("Date", "Predicted Reaction"),
        escape = FALSE) |> 
  kable_classic(full_width = F, html_font = "Cambria")|>
  pack_rows("All", 1, 4) |>
  pack_rows("Specific", 5, 11)

enter image description here

  • Related