如何在Shiny中下载可编辑的数据表 [英] How to download editable data table in shiny

查看:67
本文介绍了如何在Shiny中下载可编辑的数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在数据表中,我们可以使用参数 editable 使该表可编辑.我正在制作一个闪亮的应用程序,其中的表可以编辑和下载.

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?

这是我的应用代码:

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)

推荐答案

编辑名为"XXX"的数据表的单元格时,有关单元格编辑的信息位于 input $ XXX_cell_edit 中.该信息包含已编辑单元格的索引及其新值.因此,您可以这样做:

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)


或者,按照@MrGumble的建议,您可以使用Datatables的嵌入式按钮代替 downloadHandler .这样更时尚.

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)

这篇关于如何在Shiny中下载可编辑的数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆