首页 文章

如何在闪亮的应用程序中的同一文件中下载两个不同的数据帧

提问于
浏览
0

我有一个基本的闪亮应用程序,我想在其中下载一个包含两个不同数据帧的文件(iris,mtcars) . 这可能吗?我不关心哪一个将被显示在第一个或第二个 . 在下面的文本被破坏但我添加它是为了更清楚我想要什么 .

### ui.R

library(shiny)
pageWithSidebar(
  headerPanel('Iris k-means clustering'),
  sidebarPanel(
  uiOutput("ex") ,
  uiOutput("down")


  ),
  mainPanel(
    uiOutput('plot')

  )
)
#server.r
function(input, output, session) {
  output$ex<-renderUI({
      radioButtons("extension","File Format", choices = c("txt","csv","tsv","json"))

  })
  output$down<-renderUI({

      #Download files with quotes or not depending on the quote=input$quotes which has value TRUE or FALSE.
      output$downloadData <- downloadHandler(
        filename = function() {
          paste("file", input$extension, sep = ".")
        },

        # This function should write data to a file given to it by
        # the argument 'file'.
        content = function(file) {
          sep <- switch(input$extension,"txt"=",", "csv" = ",", "tsv" = "\t","json"=",")
          # Write to a file specified by the 'file' argument
          write.table(data.frame(iris,mtcars), file, sep = sep,
                      row.names = FALSE) 

        }

      )
      downloadButton("downloadData", "Download")
  })

}

1 回答

  • 1

    正如@ r2evans正确指出的那样,您可以在第一次调用后将 append = TRUE 添加到所有 write.table ,以便在一个文件中下载多个数据帧 .

    server.r

    server <- function(input, output, session) {
      output$ex<-renderUI({
        radioButtons("extension","File Format", choices = c("txt","csv","tsv","json"))
    
      })
      output$down<-renderUI({
        output$downloadData <- downloadHandler(
    
          #FileName
          filename = function() {
            paste("file", input$extension, sep = ".")
          },
    
          # This function should write data to a file given to it by
          # the argument 'file'.
          content = function(file) {
            sep <- switch(input$extension,"txt"=",", "csv" = ",", "tsv" = "\t","json"=",")
    
            write.table(iris, file, sep = sep, row.names = FALSE)
            write.table(mtcars, file, sep = sep, row.names = FALSE, append = TRUE)       
    
          }
    
        )
        downloadButton("downloadData", "Download")
      })
    
    }
    

相关问题