Conditional Formatting in Flextable-- any row/column with a value greater than zero to be red

Conditional formatting in flextable

  • I want any value in any row of my 7 columns of different rates to be red if the value is greater than 0
  • I have hospital unit data and rates of CLABSI’s, CAUTI’s, MDRO’s, and any value above zero is above target for our small facility, so I need them to be in red
  • the table is 7 columns-- the first column is the hospital unit, the following 6 are the rates of each type of infection for that unit, there are 4 rows of data in total for 4 hospital units

I am going to paste here the code from the R epidemiologist handbook which I tried to alter to the line below that one

  • R for epidemiologist: bg(., j=c(1:8), i= ~ hospital == “Military Hospital”, part = “body”, bg = “#91c293”)
  • how i tried to adapt: bg(j=c(2:7), i= ~ c(., >0), part = “body”, bg = “red”)

my idea is J is saying columns 2-7, and I is saying any value in any row >0 should be red

thanks for any help

1 Like

@jenmann99 thanks for posting!

It will be easier if you can share your code, ideally in a reproducible example as described here.

From what you have shared, this way is long but would work. I have not yet found a more simple way.

# load packages
library(tibble)
library(flextable)
library(tidyverse)

# create sample data
df <- tibble::tribble(
  ~hosp, ~val1, ~val2, ~val3,
  "A", 0, 0, 0, 
  "B", 0, 1, 0,
  "C", 1, 0, 1
)

# long approach
df %>% 
  qflextable() %>% 
  bg(j = 2, i = ~val1 > 0, part = "body", bg = "red") %>% 
  bg(j = 3, i = ~val2 > 0, part = "body", bg = "red") %>% 
  bg(j = 4, i = ~val3 > 0, part = "body", bg = "red") 
1 Like