【问题标题】:New conditional row in DT with rowCallback in R shinyDT 中的新条件行与 R 中的 rowCallback 闪亮
【发布时间】:2019-12-06 13:06:22
【问题描述】:

当满足某些条件时,我想在 DT 中引入一个新行。这是为了演示目的。

例如,如果某行的第一列的值为“General risk”,则之前会引入一个只有一列的新行。新列的值为“RISKS”。我有以下 rowCallback:

rowCallback = I(
                'function(row, data) {
                   if (data[1] == "General risk")
                     $("tr", row).prepend("<tr><td>RISKS</td></tr>");
                }'
               )

$("tr", row).prepend("&lt;tr&gt;&lt;td&gt;RISKS&lt;/td&gt;&lt;/tr&gt;"); 行不起作用,我不知道如何修复它。

提前致谢。

【问题讨论】:

    标签: jquery r datatable shiny dt


    【解决方案1】:

    根据official docsthis topicdatatables(R 中的DT 包)中没有用于在特定索引处添加行的 API 方法。

    您可以在 JavaScript 中通过 rowCallback 解决此问题,但我建议在 R 中创建一个临时的 data.frame(可以是反应式,这取决于您的用例)。

    代码:

    library(magrittr)
    library(DT)
    library(shiny)
    library(dplyr)
    
    # Create df for reproducible example
    df <- data.frame(
      test = c("General risk", "Category2", "Category3"),
      some_value = runif(12)
    )
    
    ui <- fluidPage(
      DT::dataTableOutput("dt")
    )
    
    server <- function(input, output, session) {
      output$dt <- DT::renderDataTable( {
        # Create temporary data.frame
        df_shown <- df
    
        # Row indeces to add
        row_indeces <- which(df$test == "General risk")
    
        # Add rows in decreasing order
        for (i in sort(row_indeces, decreasing = TRUE)) {
          df_shown <- dplyr::add_row(df_shown, test = "Risk", some_value = NA_real_, .before = i)
        }    
    
    
        datatable(
          data = df_shown,
    
          # Change bg color to stand out more
          options = list(
            rowCallback = JS("
              function( row, data, index ) {
                if (data[1] === 'Risk') {
                  $(row).css('background-color', 'Crimson');
                }
              }"
            )
          )
        )
      })  
    }
    
    shinyApp(ui, server)
    

    输出:

    【讨论】:

    • 谢谢。如果我不能用 javascript 来做,你评论的解决方案是我最后的选择。我看到了 row.add() 但我没有得到想要的结果。
    • @FrancescVE 在这种情况下我不会使用 JavaScript,因为您在 R 中有一些更好的工具,并且与 R 解决方案相比并没有太多好处。
    猜你喜欢
    • 2015-10-02
    • 2018-08-25
    • 2016-01-02
    • 2019-07-28
    • 2017-07-25
    • 2016-04-10
    • 1970-01-01
    • 2020-02-03
    • 2016-10-25
    相关资源
    最近更新 更多