【问题标题】:How can I download an object from shiny?如何从闪亮下载对象?
【发布时间】:2019-01-10 20:38:40
【问题描述】:

在尝试实现闪亮应用程序的简单下载按钮的几个问题之后,我只是尝试实现我发现的一个示例。

来源:https://www.youtube.com/watch?v=Y5arqZ9Bp0A

library(shiny)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectInput("ngear", "Select the gear number", c("1"="cyl","2"="am","3"="gear"))
    ),
    mainPanel(
      plotOutput("plot"),
      downloadButton("report","download"))
  )
)

server <- function(input, output) {
   mtreact <- reactive({
     mtcars[,c("mpg",input$ngear)]
   })

   output$plot <- renderPlot({
      with(mtreact(),boxplot(mpg~mtreact()[,2]))
   })

   output$report <- downloadHandler(
     filename = function(){
       paste("plot","png",sep=".")
     },
     content = function(){
       png(file)
       with(mtreact(),boxplot(mpg~mtreact()[,2]))
       dev.off
     }
   )
}

# Run the application 
shinyApp(ui = ui, server = server)

当我运行此代码时,闪亮的应用程序运行正常。但是,当我单击下载按钮时,会打开一个窗口以保存名为“report”的文件,该文件没有扩展名,并且不包含预期的绘图。

这是我第一次尝试这个功能。那么,有人看到代码有什么错误吗?

【问题讨论】:

  • 嗯,应该是dev.off(),而不仅仅是dev.off。为png(file) 定义的file 在哪里。也许你也想拥有content = function(file){}?另外,您是在真正的网络浏览器中运行它还是使用内置的 Rstuido 浏览器?我认为后者不支持下载文件名(但我可能错了)。见:stackoverflow.com/questions/14810409/…

标签: r shiny


【解决方案1】:

您的 downloadHandler 应该接受 content 上的文件名

   output$report <- downloadHandler(
     filename = function(){
       paste("plot","png",sep=".")
     },
     content = function(file){
                        ^^^^
       png(file)
       with(mtreact(),boxplot(mpg~mtreact()[,2]))
       dev.off
     }
   )

其次,filename 函数返回用于下载对话框的建议。然而,这在 RStudio 的应用程序查看器中没有正确执行(当您在 RStudio 中单击“运行应用程序”时出现的那个)。尝试在 Chrome 等适当的浏览器中运行该应用,以检查它是否正确响应。

【讨论】:

    【解决方案2】:

    正如 MrGumble 和 MrFlick 指出的那样,代码包含两个错误:function(file) 和 dev.of**()**

    以下代码按预期生成报告。

    library(shiny)
    
    ui <- fluidPage(
      sidebarLayout(
        sidebarPanel(
          selectInput("ngear", "Select the gear number", c("1"="cyl","2"="am","3"="gear"))
        ),
        mainPanel(
          plotOutput("plot"),
          downloadButton("report","download"))
      )
    )
    
    server <- function(input, output) {
       mtreact <- reactive({
         mtcars[,c("mpg",input$ngear)]
       })
    
       output$plot <- renderPlot({
          with(mtreact(),boxplot(mpg~mtreact()[,2]))
       })
    
       output$report <- downloadHandler(
         filename = function(){
           paste("plot","png",sep=".")
         },
         content = function(file){
           png(file)
           with(mtreact(),boxplot(mpg~mtreact()[,2]))
           dev.off()
         }
       )
    }
    

    感谢 MrFlick 和 MrGumble 的帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-14
      • 2020-04-30
      • 1970-01-01
      • 2020-09-21
      • 2013-06-25
      • 2017-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多