Search code examples
rformattable

Coloring cells of dataframe based on the condition in R


I have a dataframe like this example:

>df
id  prev_score  cur_score   change
1      10          8         -2
2      8           9          1
3      6           7          1
4      8           8          0
5      8           9          1

I would like to color prev_score column cells based on the value of change column. For example, if df$change[i] > 0, df$prev_score[i] cell color should be colored dark blue, if df$change[i] == 0, df$prev_score[i] cell color should be colored blue and if df$change[i] < 0, df$prev_score[i] cell color should be colored light blue.


Solution

  • In your question, tt is not clear if you are looking to change the color of the text or of the cell

    For the color of the text, using formattable, you can do:

    library(formattable)
    formattable(df, list(
      prev_score = formatter("span", 
                             style = ~style(font.weight = "bold", color = 
                                              ifelse(change > 0,"darkblue",
                                                     ifelse(change == 0,"blue",
                                                            ifelse(change <0, "lightblue",NA)))))
    ))
    

    enter image description here

    For coloring the box and not the text, you can do the following:

    formattable(scores, list(
      prev_score = formatter("span", 
                             style = ~style(display = "block",
                                            font.weight = "bold", 
                                            color = "white",
                                            "border-radius" = "4px",
                                            "padding-right" = "4px",
                                            "background-color" =  
                                              ifelse(change > 0,"darkblue",
                                                     ifelse(change == 0,"blue",
                                                            ifelse(change <0, "lightblue",NA)))))
    ))
    

    enter image description here

    Does it answer your question ?

    Reproducible example

    df <- data.frame(id = 1:5,
                         prev_score = c(10, 8, 6, 8, 8),
                         cur_score = c(8, 9, 7, 8, 9),
                         change = c(-2, 1, 1, 0, 1))