Search code examples
rshinydtflexdashboard

Empty dataTable after saving in shiny


I create a reactive and editable matrix with dataTable in the shiny flex dashboard but when I try to save it as a CSV file it's empty

### Chart A

```{r}

      numericInput("num_hos", "Number of hospitals:", value = 2)
      numericInput("num_qua", "Number of quantities:", value = 2)
      actionButton("create", "Create an empty Matrix")
```



Column {data-width=350}
-----------------------------------------------------------------------

### Chart C

```{r}
data <- eventReactive(input$create,{
  matrix(nrow = input$num_hos+2,ncol = input$num_qua+1)
})

renderDataTable(data(),server = T,editable=list(target = "column"),
extensions = 'Buttons',options = list(dom = 'Blfrtip',buttons=c('copy', 'csv', 'excel', 'pdf', 'print'),
lengthMenu = list(c(10,25,50,-1),
  c(10,25,50,"All"))))
```

Solution

  • The code below works, but I use editable = list(target = "cell"), because I didn't manage with "column": I don't know how to validate the edits (with "cell" I just click somewhere).

    ---
    title: "Untitled"
    output: flexdashboard::flex_dashboard
    date: "2023-03-20"
    runtime: shiny_prerendered
    ---
    
    ```{r, context='setup', include=FALSE}
    library(DT)
    library(shiny)
    ```
    
    ### Chart A
    
    ```{r}
    fillCol(
      height = 600, flex = c(NA, 1), 
      inputPanel(
        numericInput("num_hos", "Number of hospitals:", value = 2),
        numericInput("num_qua", "Number of quantities:", value = 2),
        actionButton("create", "Create an empty Matrix")
      ),
      DTOutput("dtable", height = "100%")
    )
    ```
    
    Column {data-width=350}
    -----------------------------------------------------------------------
    
    ### Chart C
    
    ```{r, context='server'}
    dat <- NULL
    data <- eventReactive(input$create, {
      dat <<- matrix(nrow = input$num_hos+2, ncol = input$num_qua+1)
      dat
    })
    
    output[["dtable"]] <- renderDT({
      datatable(
        data(), 
        editable = list(target = "cell"),
        extensions = "Buttons", 
        options = list(
          dom = 'Blfrtip', 
          buttons=c('copy', 'csv', 'excel', 'pdf', 'print'),
          lengthMenu = list(c(10, 25, 50, -1), c(10, 25, 50, "All"))
        )
      )
    })
    
    proxy <- dataTableProxy("dtable")
    
    observeEvent(input[["dtable_cell_edit"]], {
      dat <<- editData(dat, input[["dtable_cell_edit"]], proxy, rownames = FALSE)
    })
    ```