Search code examples
rconditional-formattingflextable

Flextable Basic Conditional Formatting


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


Solution

  • 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)