Custom Buttons in R DT Tables II

A few months ago I wrote a short post on how to define custom button logic for R DT tables. Since then my Javascript knowledge slightly improved and I was able to implement this cleaner while also fixing a flaw in the previous solution.

The old approach did not preserve previous sorting on table columns. This sounds like a minor annoyance but actually makes the user experience significantly worse. The fix below makes use of DT’s built-in search functionality which preserves sorting.

One slight difference in behavior is that the button logic will also keep non-exact matches in the table as you would expect from a search functionality. Below we are filtering for Mazda RX4, but as you can see after the button click we still also show Mazda RX4 Wag.

library("DT")

datatable(mtcars,
          extensions = 'Buttons',
          options = list(
            dom = 'Brt',
            buttons = list(
              list(
                extend = 'collection',
                text = 'Filter',
                action = DT::JS("function ( e, dt, node, config ) {
                                   dt.column(0).data().search('').draw(false);
                                   dt.column(0).data().search('Mazda RX4').draw(true);
                                }")
              ),
              list(
                extend = 'collection',
                text = 'Restore',
                action = DT::JS("function ( e, dt, node, config ) {
                                   dt.column(0).data().search('').draw(true);
                                }")
              )
            )
          )
)
library("DT")

d2 <- datatable(mtcars,
          extensions = 'Buttons',
          options = list(
            dom = 'Brt',
            buttons = list(
              list(
                extend = 'collection',
                text = 'Filter',
                action = DT::JS("function ( e, dt, node, config ) {
                                   dt.column(0).data().search('').draw(false);
                                   dt.column(0).data().search('Mazda RX4').draw(true);
                                }")
              ),
              list(
                extend = 'collection',
                text = 'Restore',
                action = DT::JS("function ( e, dt, node, config ) {
                                   dt.column(0).data().search('').draw(true);
                                }")
              )
            )
          )
)