6

I have a flextable that I am trying to conditionally format percentage numbers based if they are > or less than a certain %. It's a simple conditional format so I'm not sure why it's not working. I feel as though I'm missing something obvious here.

Here is an example:


myft = structure(list(Name = c("Bob", "Fred", "Joe"), `2020-03-30` = c(96, 
                                                                       100, 36)), row.names = c(NA, -3L), class = c("tbl_df", "tbl", 
                                                                                                                    "data.frame"))
myft = flextable(myft)


myft = bg(myft, i = ~ Name  > 50,
            j = 2,
            bg="red")
myft

This code produces this image:

enter image description here

vb66
  • 353
  • 3
  • 14

1 Answers1

17

You want to use the conditional formatting based on the "2020-03-30" column:

library(flextable)
myft = structure(list(Name = c("Bob", "Fred", "Joe"), `2020-03-30` = c(96, 
                                                                       100, 36)), row.names = c(NA, -3L), class = c("tbl_df", "tbl", 
                                                                                                                    "data.frame"))
myft = flextable(myft)


myft = bg(myft, i = ~ `2020-03-30`  > 50, 
          j = 2,
          bg="red")
myft

Edit:

If you want conditional coloring across multiple columns, you could create a color matrix:

library(flextable)
myft = structure(list(Name = c("Bob", "Fred", "Joe"), 
                      `2020-03-30` = c(96, 100, 36),
                      `2020-04-30` = c(30, 100, 36)), 
                 row.names = c(NA, -3L), class = c("tbl_df", "tbl", "data.frame"))

colormatrix <- ifelse(myft[, -1] > 50, "red", "white")
myft %>% flextable() %>% bg(j = 2:3, bg=colormatrix)

user12728748
  • 8,106
  • 2
  • 9
  • 14
  • Knew it was something obvious. Now though, I've tried to apply this to all of the columns with dates using a vector with all of the dates in i and j. If I had many date columns, how could I continue to apply this? – vb66 Jul 04 '20 at 14:47
  • Perhaps have a look at https://stackoverflow.com/questions/58677080/r-flextable-conditional-formatting-based-on-pairs-of-rows how to create a color grid. – user12728748 Jul 04 '20 at 14:57
  • Your edit above worked like a dream!! Thank you! That's going to really come in handy and save me a ton of time. – vb66 Jul 04 '20 at 19:21