Search code examples
rdataframeconditional-formatting

Using condformat package to format dataframe


I'm trying to conditionally colour three columns in my df using the condformat package. I have succeeded with one (Percentage), but can't understand why the others (AnswerA and AnswerB) aren't working. I'd really appreciate any guidance.

Here's my code:

library(condformat)

my_df <- data.frame(
  Percentage = runif(10),
  AnswerA = c("A", "A", "B", "B", "C", "C", "D", "D", "E", "E"),
  AnswerB = c("A", "A", "A", "B", "C", "C", "D", "D", "D", "E")
)

my.df.cf <- condformat(my_df) %>%
  ## Highlight Percentages below 20% or above 80%
  rule_fill_discrete('Percentage',
                     expression = cut(Percentage, breaks = c(0, 0.2, 0.8, 1), include.lowest = TRUE, labels = FALSE),
                     colours = c('1' = 'firebrick1', '2' = 'white', '3' = 'lightgreen')) %>%
  ## Highlight when answers A and B don't match
  rule_fill_discrete(c('AnswerA','AnswerB'),
                     expression = AnswerA != AnswerB ,
                     colours = c('TRUE' = 'firebrick1', 'FALSE' = 'white')) 

Solution

  • Your code is working, except for color firebrick1.

    Try with hex code instead:

    condformat(my_df) %>%
      ## Highlight Percentages below 20% or above 80%
      rule_fill_discrete(
        columns = Percentage,
        expression = cut(
          Percentage, 
          breaks = c(0, 0.2, 0.8, 1), 
          include.lowest = TRUE, 
          labels = FALSE),
        
        colours = c(
          '1' = '#FF3030', 
          '2' = '#FFFFFF', 
          '3' = '#90EE90')) %>%
      
      ## Highlight when answers A and B don't match
      rule_fill_discrete(
        columns = contains("Answer"),
        expression = AnswerA != AnswerB,
        colours = c(
          'TRUE' = '#FF3030', 
          'FALSE' = '#FFFFFF')) 
    

    The output:

    condformat pkg img output