【问题标题】:R DT conditional formatting using non visible column使用不可见列的 R DT 条件格式
【发布时间】:2018-09-05 11:15:49
【问题描述】:

这个问题与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')))

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

  • 如果Speciessetosa 那么蓝色和
  • 如果Speciesversicolor,那么红色和
  • 如果Speciesvirginica 则为绿色

【问题讨论】:

    标签: r shiny dt


    【解决方案1】:

    这应该可以完成工作

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

    【讨论】:

    • 比我的回答简单。 +1
    【解决方案2】:

    这里有一个解决方案:

    • 使用完整的数据集;
    • 使用选项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')))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-19
      • 2018-02-06
      • 2019-12-17
      • 2019-01-06
      • 2018-08-25
      • 2017-11-18
      • 2019-05-16
      • 2016-11-20
      相关资源
      最近更新 更多