R中DataTable中的条件格式化单元格

Conditional formatting cell in DataTable in R

到目前为止,我有以下代码作为示例:

library(DT)

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

我有兴趣根据条件仅突出显示特定的 "cell"。

例如,如果 iris[3, 2] > 3.1 那么背景颜色应该是黄色。

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

sessionInfo() DT_0.1

您可以使用 DT Helper Functions 执行此操作。有一个函数可以为特定间隔 (styleInterval()) 设置单元格样式,或者如果单元格值等于某个值 (styleEqual())。 styleEqual()好像不支持条件直接输入,不过你可以先计算条件(也可以另建一列)再用。

如上面链接的页面(在第 2 节 "Style Table Cells" 下)所述,您可以这样做,例如:

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