Phil
Phil

Reputation: 8127

Conditionnally formatting the background color of a table (formattable in R)

I have a table similar to the below:

library(tibble)
library(formattable)

mytable <- tibble(
id = c(NA, 748, 17, 717, 39, 734, 10, 762),
NPS = c(65, 63, 56, 62, 73, 80, 50, 54),
`NPS Chge vs. month ago` = c(-2, -5, -2, -8, -1, 6, 7, -9),
`Cumulative Response` = c(766, 102, 154, 81, 239, 79, 50, 61),
`Response Rate` = c(0.25, 0.24, 0.25, 0.34, 0.21, 0.34, 0.32, 0.27),
`Response for Month` = c(161, 43, 7, 37, 7, 32, 15, 20)
)

formattable(mytable)

enter image description here

And I wish to set a conditional formatting to the background of the rows such that if the NPS score is below 60 the background is set to red, otherwise it's set to green. In my limited knowledge of HTML I figured I could use "td". Unfortunately it appears to mess the format of the table as a whole:

html_tag <- "td"
my_format <- formatter(html_tag, style = x ~ ifelse(mytable$NPS < 60, "background-color:red", "background-color:green"))

formattable(mytable, list(
  area(col = 2:6) ~ my_format
))

enter image description here

The headers of the table are no longer aligned with the rest of the rows. What am I doing wrong? What should I use instead of "td"?

Upvotes: 2

Views: 2684

Answers (1)

ETeddy
ETeddy

Reputation: 171

You can also change the background color conditionally without using HTML. A simple version of code without extra aesthetics could be like this:

library(dplyr)
library(formattable)
tibble(
  id = c(NA, 748, 17, 717, 39, 734, 10, 762),
  NPS = c(65, 63, 56, 62, 73, 80, 50, 54),
  `NPS Chge vs. month ago` = c(-2, -5, -2, -8, -1, 6, 7, -9),
  `Cumulative Response` = c(766, 102, 154, 81, 239, 79, 50, 61),
  `Response Rate` = c(0.25, 0.24, 0.25, 0.34, 0.21, 0.34, 0.32, 0.27),
  `Response for Month` = c(161, 43, 7, 37, 7, 32, 15, 20)
) %>%
  formattable(align = rep("c", ncol(.)),
              list(
                `NPS` = formatter("span", style = ~ style (display = "block",
                                                           `background-color` = ifelse(NPS < 60, "red", "green"))) 
              )
  )

enter image description here

Upvotes: 0

Related Questions