1

I would like to introduce a new row in the DT when some condition is met. It is for presentation purposes.

For example, if the first column has the value "General risk" in some row, then a new row with only one column is introduced before. The new column will have the value "RISKS". I have the following rowCallback:

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

The line $("tr", row).prepend("<tr><td>RISKS</td></tr>"); doesn't work and I don't know how to fix it.

Thanks in advance.

Francesc VE
  • 762
  • 2
  • 9
  • 19

1 Answers1

2

According to official docs and this topic there is no API method in datatables (DT package in R) for adding rows at specific indeces.

You can solve this via rowCallback in JavaScript, but I would suggest creating a temporary data.frame in R (can be a reactive, it depends on your use case).

Code:

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)

Output:

output

GyD
  • 3,902
  • 2
  • 18
  • 28
  • Thanks. The solution that are you commenting was my last option if I couldn't do it with javascript. I saw the row.add() but I don't get with the desired result. – Francesc VE Jul 31 '19 at 07:27
  • @FrancescVE I wouldn't bother with JavaScript in this case, as you have some better tools in R, and there is not much benefit over the R solution. – GyD Jul 31 '19 at 08:26