如何在R中的数据帧/表中对特定单元格进行着色? [英] How to color specific cells in a Data Frame / Table in R?

查看:144
本文介绍了如何在R中的数据帧/表中对特定单元格进行着色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为以下数据帧中的特定单元格着色。例如,在inputval列中,我要突出显示 [0.8,0.9)品红色范围内的单元格,并且 [0.7,0.8)蓝色。类似地,我希望值为1的输出列单元格被着色为洋红色,而值为4的输出列单元格被着色为蓝色。对于数据帧中的其余单元格,我希望它们保持白色。

I would like to color specific cells in the following dataframe. For example, in the inputval column, I would like to highlight cells in the range of [0.8, 0.9) magenta, and the cells in that same column in the range of [0.7, 0.8) blue. Similarly, I'd like the output column cells with a value of 1 to be colored magenta and those with value 4 to be colored blue. For the rest of the cells in the dataframe, I would like them to remain white.

我有以下可重现的代码,它仅按行突出显示,并且限制着只在品红色和白色的着色。如何添加另一种颜色,并按单元格这样做?

I have the following reproducible code which highlights by row only, and limits me to coloring in magenta and white only. How can I add another color and do so by cell?

set.seed(123)
df <- data.frame(id       = sample(1:100, 20, replace = TRUE),
                 inputval = sample(seq(0, 1, by=0.01), 20, replace = TRUE),
                 outcome  = sample(1:4, 20, replace = TRUE))

cols <- with(df, ifelse(outcome == 1, 'magenta', 'white'))

library('htmlTable')
htmlTable(as.matrix(df), col.rgroup = cols)

$ b b

我意识到添加不同颜色的问题是中调用 if 这限制了我只是洋红色和白色。如何在这里添加另一个条件?

I realize that the issue for adding different colors is with the ifelse call in with that limits me to just magenta and white. How can I add another condition here?

虽然我知道是什么导致多个颜色问题,但我对如何只对特定的单元格进行着色很无能。

While I know what's causing the multiple color issue, I'm pretty clueless about how to color only specific cells.

这个例子与此问题的接受答案
谢谢!

This is the same example as the accepted answer to this question. Thanks!

推荐答案

您是否考虑过 DT

library(DT)
datatable(df, rownames = FALSE) %>%
  formatStyle(columns = "inputval", 
              background = styleInterval(c(0.7, 0.8, 0.9)-1e-6, c("white", "lightblue", "magenta", "white"))) %>%
  formatStyle(columns = "outcome", 
              background = styleEqual(c(1, 4), c("magenta", "lightblue"))) 

这篇关于如何在R中的数据帧/表中对特定单元格进行着色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆