简体   繁体   中英

Replace data in R formattable datatable using replaceData function

I need to replace data in a (formattable) datatable smoothly without the page flashing while re-loading.

Following the example from @yihui here: https://github.com/rstudio/DT/issues/168 I have managed to replace data in a standard datatable smoothly without the page flashing using the dataTableProxy function.

When including the formatting via the formattable package my code throws an error: Warning: Error in as.data.frame.default: cannot coerce class "c("datatables", "htmlwidget")" to a data.frame

Minimal reproducible example:

library(shiny)
library(DT)
library(formattable)

dt <- data.frame(type = letters[1:5], count = sample(1:10, 5))

shinyApp(
    ui = fluidPage(sidebarLayout(
        sidebarPanel(
            sliderInput(
                "number",
                "Select:",
                min = 0,
                max = 10,
                value = 8
            )
        ),

        mainPanel(DT::dataTableOutput('DTtable'))
    )),

    server = function(input, output, session) {
        # Reactive expression of the data frame, subset by the slider number
        sliderValues <- reactive({
            # Compose data frame
            dt['count' > input$number,]
        })


        output$DTtable = DT::renderDataTable(as.datatable(formattable(
            isolate(sliderValues()),

            list(count = color_tile('#ffffff', '#6be560'))
        )))


        observeEvent(sliderValues(), ignoreInit = T, {
            replaceData(dataTableProxy('DTtable'),

                as.datatable(formattable(
                    isolate(sliderValues()),

                    list(count = color_tile('#ffffff', '#6be560'))
                )))
        })
    }
)

When I move the slider I would like the table to reload whilst also retaining the formattable styling.

Small error in sliderValues . Replace with

sliderValues <- reactive({
  # Compose data frame
  dt[dt$count > input$number,]
})

Now, replaceData requires a dataframe in the second argument, not a datatable. That's why you get this error. When you have a datatable dtable , the dataframe is in dtable$x$data . But there is an additional column for the rownames, which must be removed. So do:

observeEvent(sliderValues(), ignoreInit = TRUE, {
  replaceData(dataTableProxy('DTtable'),
              as.datatable(formattable(
                isolate(sliderValues()),
                list(count = color_tile('#ffffff', '#6be560'))
              ))$x$data[,-1]
  )
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM