rflextable

How to color background in flextable for categorical values and not numeric


I have the dataframe with 2 categorical columns. all examples I found is for numeric values

library(flextable)

data <- data.frame( MCP = c("Y", "N", "Y", "N", "Y"),
                    RCP = c("N", "Y", "N", "Y", "N"))
# Create flextable
ft <- flextable(data)

I want to color background of the cells to green if the values is y and red if it is N: I could not find a way to do it, package documentation only has it for continuous data


Solution

  • library(dplyr)
    ft %>% 
      bg(~ MCP == "N", ~ MCP, bg="red") %>% 
      bg(~ RCP == "N", ~ RCP, bg="red") %>% 
      bg(~ MCP == "Y", ~ MCP, bg="green") %>% 
      bg(~ RCP == "Y", ~ RCP, bg="green")    
    

    enter image description here