Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 984
vb66 Avatar asked Aug 27 '26 17:08

vb66


1 Answers

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)

like image 195
user12728748 Avatar answered Aug 29 '26 06:08

user12728748



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!