简体   繁体   English

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

[英]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.我想根据change列的值为prev_score列单元格着色。 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.例如, if df$change[i] > 0 ,则df$prev_score[i]单元格颜色应为深蓝色, if df$change[i] == 0 ,则df$prev_score[i]单元格颜色应为蓝色if df$change[i] < 0df$prev_score[i]单元格颜色应为浅蓝色。

In your question, tt is not clear if you are looking to change the color of the text or of the cell在您的问题中,tt不清楚您是否要更改文本或单元格的颜色

For the color of the text, using formattable , you can do:对于文本的颜色,使用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)))))
))

在此处输入图片说明

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

在此处输入图片说明

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM