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

时间:2015-06-09 21:02:36

标签: r datatables

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

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 个答案:

答案 0 :(得分:2)

您可以使用DT Helper Functions执行此操作。有一个函数可以为单元格设置一定的间隔(styleInterval()),或者单元格值等于(styleEqual())。 styleEqual()似乎不支持条件的直接输入,但您可以先计算条件(可能为其创建另一列),然后再使用它。

如上面链接的页面(在第2节和第34节;样式表单元格"中)所述,您可以这样做:

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')
    )
  )
相关问题