下载在 R Shiny 中的 renderTable 输出中独立生成的表

Gom*_*mpu 1 r shiny

我正在尝试使用 R Shiny 中的 renderTable 函数生成一个表,然后使用 downloadHandler 函数将该表/data.frame 下载为 csv 文件。不知怎的,我不断收到以下错误:

下载期间发生错误:下载http://127:0:0.1:3001/session/ 0303bd426fce88837ae277aa3b406dd/download/downloadData?w=时出错 - 服务器回复:内部服务器错误

下面是一个示例代码,我在其中生成一个简单的数据帧并尝试使用 downloadHander 下载它:

library(shiny)
 # Define UI for data download app ----
ui <- fluidPage(

    # App title ----
    titlePanel("Downloading Data"),

    # Sidebar layout with input and output definitions ----
    sidebarLayout(

        # Sidebar panel for inputs ----
        sidebarPanel(
            # Button
            downloadButton("downloadData", "Download")

        ),

        # Main panel for displaying outputs ----
        mainPanel(

            tableOutput("table")

        )

    )
)
# Define server logic to display and download selected file ----
server <- function(input, output) {

    # Table of selected dataset ----
    output$table <- renderTable({
        data.frame(a =c(1,2,3),b=c("q","s","f"))
    })

    # Downloadable csv of selected dataset ----
    output$downloadData <- downloadHandler(
        filename = function() {
            paste("test.csv")
        },
        content = function(file) {
            write.csv(output$table, file, row.names = FALSE)
        }
    )

}
shinyApp(ui,server)
Run Code Online (Sandbox Code Playgroud)

小智 5

这里需要做一些事情:

  1. 如果您的应用程序要动态渲染数据,那么您的数据应该分配给某个reactive表达式。
  2. 现在数据的下载变得很容易,只需调用reactive(1)中编写的表达式即可。
    • 上述第 (1) 点和第 (2) 点将确保用户下载的数据与屏幕上看到的数据相同。

请尝试以下操作:

library(shiny)

ui <- fluidPage(
  titlePanel("Downloading Data"),
  sidebarLayout(
    sidebarPanel(downloadButton("downloadData", "Download")),
    mainPanel(tableOutput("table"))
  )
)

server <- function(input, output) {

  data <- shiny::reactive(data.frame(a = c(1, 2, 3), b = c("q", "s", "f")))
  output$table <- renderTable(data())

  output$downloadData <- downloadHandler(
    filename = function() {
      paste("test.csv")
    },
    content = function(file) {
      write.csv(data(), file, row.names = FALSE)
    }
  )

}
shinyApp(ui,server)
Run Code Online (Sandbox Code Playgroud)