Flextable Basic Conditional Formatting
Asked Answered
B

1

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

Banda answered 4/7, 2020 at 14:7 Comment(0)
F
18

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)

Flite answered 4/7, 2020 at 14:35 Comment(3)
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?Banda
Perhaps have a look at #58677580 how to create a color grid.Flite
Your edit above worked like a dream!! Thank you! That's going to really come in handy and save me a ton of time.Banda

© 2022 - 2024 — McMap. All rights reserved.