使用不可见列的R DT条件格式

时间:2018-09-05 11:15:49

标签: r shiny dt

这个问题与this有关,但是我要限定的值不是单元格的值,而是一个可用的外部列,但未在DT中显示。

我的例子很简单:

DT::datatable(
  iris[,1:4],
  editable = TRUE,
  filter = c("bottom"),
  rownames = FALSE,
  extensions = 'Buttons',
  options = list(
    pageLength=21, scrollY='400px',
    dom = 'Brt'
))%>% formatStyle('Sepal.Length', fontWeight = styleInterval(5, c('normal', 'bold')))

如何根据Sepal.Length的值对列iris$Species进行颜色编码或应用格式

  • 如果Speciessetosa,则为蓝色,并且
  • 如果Speciesversicolor,则为红色,并且
  • 如果Speciesvirginica,则为绿色

2 个答案:

答案 0 :(得分:2)

这应该可以完成

library(DT)
DT::datatable(
  iris,
  editable = TRUE,
  filter = c("bottom"),
  rownames = FALSE,
  extensions = 'Buttons',
  options = list(
    columnDefs = list(list(targets = 4, visible = F)),
    pageLength= 150, scrollY='400px',
    dom = 'Brt'
  )) %>% formatStyle(
    'Sepal.Length', 'Species',
    backgroundColor = styleEqual(c("setosa", "versicolor","virginica"), c('steelblue', 'red', "green"))
  )

enter image description here

答案 1 :(得分:1)

这是一个解决方案:

  • 使用完整的数据集;
  • 使用选项columnDefs隐藏所需的列;
  • 在选项initComplete中使用一些Javascript设置颜色。

jscode <- "function(settings) {
var table = settings.oInstance.api();
var nrows = table.rows().count();
for(var i=0; i<nrows; i++){
var cell0 = table.cell(i,0);
var cell4 = table.cell(i,4);
var species = cell4.data();
var bgcolor;
if(species == 'setosa'){
bgcolor = 'blue';
}else if(species == 'versicolor'){
bgcolor = 'red';
}else{
bgcolor = 'green'
}
cell0.node().style.backgroundColor = bgcolor;
}
}"

DT::datatable(
  iris,
  editable = TRUE,
  filter = c("bottom"),
  rownames = FALSE,
  extensions = 'Buttons',
  options = list(
    pageLength=21, scrollY='400px',
    dom = 'Brtp',
    columnDefs = list(list(visible=FALSE, targets=4)),
    initComplete = JS(jscode)
  ))%>% formatStyle('Sepal.Length', 
                    fontWeight = styleInterval(5, c('normal', 'bold')))

enter image description here