Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download editable data table in shiny

Tags:

r

dt

shiny

In data table, we can use argument editable to make the table editable. I'm making a shiny app in which table is both editable and downloadable.

My question is how I can download a datatable after I edit it?

Here is my app code:

library(shiny)
library(DT)

server <- function(input, output) {

    df = iris

    output$data = DT::renderDataTable ({
        DT::datatable(df, editable = list(
            target = 'row', 
            disable = list(columns = c(1, 3, 4))
        ))

    })


    output$downloadData <- downloadHandler(
        filename = function() {
            #paste(input$dataset, ".csv", sep = "")
        },
        content = function(file) {
            write.csv(df, file, row.names = FALSE)
        }
    )
}

ui <- fluidPage(

    DT::dataTableOutput('data'),
    downloadButton("downloadData", "Download")
)

shinyApp(ui = ui, server = server)
like image 538
zesla Avatar asked Dec 13 '22 11:12

zesla


1 Answers

When you edit a cell of a datatable named "XXX", the info about the cell edit is in input$XXX_cell_edit. This info contains the indices of the edited cell and its new value. So you can do:

library(shiny)
library(DT)

dat <- iris[1:3, ]

ui <- fluidPage(
  downloadButton("downloadData", "Download"),
  DTOutput("table")
)

server <- function(input, output){

  output[["table"]] <- renderDT({
    datatable(dat, editable = "cell")
  })

  df <- reactiveVal(dat)

  observeEvent(input[["table_cell_edit"]], {
    cell <- input[["table_cell_edit"]]
    newdf <- df()
    newdf[cell$row, cell$col] <- cell$value
    df(newdf)
  })

  output[["downloadData"]] <- downloadHandler(
    filename = function() {
      "mydata.csv"
    },
    content = function(file) {
      write.csv(df(), file, row.names = FALSE)
    }
  )

}

shinyApp(ui, server)

Alternatively, as suggested by @MrGumble, you can use the embedded button of Datatables instead of a downloadHandler. This is more stylish.

library(shiny)
library(DT)

dat <- iris[1:3, ]

ui <- fluidPage(
  DTOutput("table")
)

server <- function(input, output){

  output[["table"]] <- renderDT({
    datatable(dat, editable = "cell", extensions = "Buttons", 
              options = list(
                dom = "Bfrtip",
                buttons = list(
                  "csv"
                )
              ))
  })

  observeEvent(input[["table_cell_edit"]], {
    cellinfo <- input[["table_cell_edit"]]
    dat <<- editData(dat, input[["table_cell_edit"]], "table")
  })


}

shinyApp(ui, server)
like image 78
Stéphane Laurent Avatar answered Dec 27 '22 19:12

Stéphane Laurent