根据R中的条件为数据框的单元格着色

时间:2020-02-22 03:46:14

标签: r formattable

我有一个像这样的数据框:

>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

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

1 个答案:

答案 0 :(得分:2)

在您的问题中,如果要更改文本或单元格的颜色,tt尚不清楚

对于文本的颜色,可以使用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)))))
))

enter image description here

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

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

它回答了您的问题吗?

可复制的示例

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