根据R中的条件对数据框的单元格进行着色

Coloring cells of dataframe based on the condition in R

我有一个像这个例子的数据框:

>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

我想根据 change 列的值为 prev_score 列单元格着色。例如,if df$change[i] > 0df$prev_score[i] 单元格颜色应为深蓝色,if df$change[i] == 0df$prev_score[i] 单元格颜色应为蓝色,if df$change[i] < 0df$prev_score[i] 单元格颜色应为浅蓝色。

在您的问题中,不清楚您是要更改文本颜色还是单元格颜色

对于文本的颜色,使用formattable,你可以这样做:

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

要为框而不是文本着色,您可以执行以下操作:

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

它是否回答了您的问题?

可重现的例子

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