首页 > 解决方案 > 在 R Shiny 中下载反应表的输出

问题描述

我有一个 R 闪亮的应用程序,它从用户那里获取 .csv 导入,并在内置数据框中搜索导入的数据,然后在输出中给出匹配百分比。UI 非常简单,有几个不同的输入(导入 .csv、一个滑块和一些单选按钮)。我想要的是能够获取反应表输出并将其打印到用户可以下载到他们的机器的 .csv 中。应用程序的服务器端如下所示:

server <- function(input, output){
    rvals <- reactiveValues()

    observeEvent(input$file_1,{
        req(input$file_1)
        rvals$csv <<- read.csv(input$file_1$datapath, header = TRUE)
        #some data processing here
  })

    output$contents <- renderTable({
        if(input$select == 1){
        x <- function
        }else if(input$select == 2){
        x <- function
        }else if(input$select == 3){x <- function}

        #some more data processing and formatting here

        return(x)

    },digits = 4)
}

我希望数据表 x 能够成为可以通过单击下载按钮下载的 .csv。在服务器中,我添加了以下代码,但是当我尝试下载数据时,它只会下载一个空白文件并在我机器上的下载管理器中显示“服务器错误”。

output$downloadData <- downloadHandler(
    filename = "thename.csv",
    content = function(file){
      write.csv(x, file)
    }

在控制台中,我还收到错误消息: Warning: Error in is.data.frame: object 'x' not found [No stack trace available]

标签: rshiny

解决方案


您在表达式内部创建的对象在其renderTable外部不可用。相反,您可以将其分配给您设置的反应值。下面是一个工作示例(请注意,我已尝试复制您的代码,因此在您单击“上传 CSV”之前数据将不可用,此处仅调用mtcars)。

library(shiny)

ui = fluidPage(

  sidebarPanel(
    actionButton(inputId = "uploadCsv", label = "Upload CSV:", icon = icon("upload")),
    selectInput(inputId = "preProc", label = "Pre-processing", choices = c("Mean"=1,"Sum"=2)),
    downloadButton("downloadData", label = "Download table")
  ),

  mainPanel(
    h4("My table:"),
    tableOutput("contents")
  )

)

server <- function(input, output) {

  rvals <- reactiveValues(
    csv=NULL,
    x=NULL
  )

  observeEvent(input$uploadCsv,{
    rvals$csv <- mtcars # using example data since I don't have your .csv
    # rvals$csv <- read.csv(input$file_1$datapath, header = TRUE) 
    #some data processing here
  })

  output$contents <- renderTable({
    # Assuing the below are functions applied to your data
    req(
      input$preProc,
      !is.null(rvals$csv)
    )
    if(input$preProc == 1){
      rvals$x <- data.frame(t(colMeans(mtcars)))
    }else {
      rvals$x <- data.frame(t(colSums(mtcars)))
    }

    return(rvals$x)

  },digits = 4)

  output$downloadData <- downloadHandler(
    filename = "myFile.csv",
    content = function(file){
      write.csv(rvals$x, file)
    }
  )
}

shinyApp(ui,server)

推荐阅读