在R中的数据表(DataTable)中,如何对单元格进行条件格式设置?

11

我已经有了以下的示例代码:

library(DT)

datatable(iris, options = list(pageLength = 5)) %>%
  formatStyle(
    'Sepal.Width',
    backgroundColor = styleInterval(3, c('gray', 'yellow'))
)

我只对基于条件的特定“单元格”进行突出显示感兴趣。

例如,如果iris [3, 2]> 3.1,则背景颜色应为黄色。

参考http://rstudio.github.io/DT/

sessionInfo() DT_0.1

1个回答

13
你可以使用DT助手函数来完成这个任务。有一个函数可以对特定区间的单元格进行样式设置 (styleInterval()),或者如果单元格的值等于某个值则进行样式设置 (styleEqual()) 。似乎styleEqual()不支持直接输入条件,但你可以先计算条件 (也许可以为此创建另一列),然后再使用它来达到目的。
如上面链接页面所述(第2节“样式表单元格”),你可以像下面这样实现:
datatable(iris) %>% 
  formatStyle('Sepal.Length', fontWeight = styleInterval(5, c('normal', 'bold'))) %>%
  formatStyle(
    'Sepal.Width',
    color = styleInterval(c(3.4, 3.8), c('white', 'blue', 'red')),
    backgroundColor = styleInterval(3.4, c('gray', 'yellow'))
  ) %>%
  formatStyle(
    'Petal.Length',
    background = styleColorBar(iris$Petal.Length, 'steelblue'),
    backgroundSize = '100% 90%',
    backgroundRepeat = 'no-repeat',
    backgroundPosition = 'center'
  ) %>%
  formatStyle(
    'Species',
    transform = 'rotateX(45deg) rotateY(20deg) rotateZ(30deg)',
    backgroundColor = styleEqual(
      unique(iris$Species), c('lightblue', 'lightgreen', 'lightpink')
    )
  )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接