只在Shiny R主面板中出现输出时才显示下载按钮

8

我有以下代码,可以接受csv文件->运行R代码->显示->下载输出。

但是,下载按钮会在应用程序运行时立即出现。 有没有办法仅在输出文件可用时显示输出按钮?

下面是我正在使用的代码:

UI.R

library(shiny)

#ui.R
# Define UI for random distribution application 
shinyUI(fluidPage(

  # Application title
  titlePanel("Text Mining on R"),

  sidebarLayout(
    sidebarPanel(
      fileInput('file1', 'Select the Input File',
                accept=c('text/csv','text/comma-separated-values,text/plain','.csv')),
      tags$hr(),
      fileInput('file2', 'Select the UserTopic file',
                accept=c('text/csv','text/comma-separated-values,text/plain','.csv'))

    ),
    mainPanel(
      dataTableOutput('table'),
      downloadButton('OutputFile', 'Download Output File')
    )
  ))
)

Server.R

#server.R
library(shiny)

shinyServer(function(input, output) {

  observe({
    file1 = input$file1
    file2 = input$file2
    if (is.null(file1) || is.null(file2)) {
      return(NULL)
    }
    data1 = read.csv(file1$datapath,header = TRUE, sep=",",skipNul = TRUE)
    data2 = read.csv(file2$datapath,header = TRUE, sep=",",skipNul = TRUE)
   source("RCode.R", local = TRUE)
    #output$table <- renderDataTable(output2)
    output$table <- renderDataTable({
      my_function(file1$datapath,file2$datapath)
    })

    output$OutputFile <- downloadHandler(


      filename = function() {
        paste("OutputFile", "_",Sys.time(),".csv",sep="")
       },

      content = function(file) {


        write.csv(my_function(file1$datapath,file2$datapath), file, sep = ",",
                    row.names = FALSE)
      }
    )
  })

})

谢谢!
4个回答

10

在服务器端,您可以使用以下内容:

output$download <- renderUI({
  if(!is.null(input$file1) & !is.null(input$file2)) {
    downloadButton('OutputFile', 'Download Output File')
  }
})

在UI方面,您需要将下载按钮替换为:

uiOutput("download")

8
你可以使用req()。
在用户界面中:
uiOutput("get_the_item")

在服务器中:

output$get_the_item <- renderUI({
req(input$file1, input$file2)
downloadButton('download_item', label = 'Download item') })

在renderUI下方,添加downloadHandler(使用您的文件名和内容参数完成代码):
output$download_item <- downloadHandler(
filename = function() {},
content = function(file) {}
)

强烈建议使用req()。来自https://shiny.rstudio.com/articles/req.html: "当您使用req检查前提条件时,失败不仅会停止当前计算...,还会停止调用堆栈上的任何调用者。" - Megatron

4
一个简单的方法来在一个 shiny 网页应用中隐藏/显示对象,是使用来自Dean Attali的令人惊叹的shinyjs包。这个包有广泛的文档,并且你可以在Dean博客的这个页面上找到完整的可工作的示例集。

3

除了上述解决方案之外,您还可以使用以下方式中的conditionalPanel

ui.R

conditionalPanel("output.fileUploaded",
                   downloadButton('OutputFile', 'Download Output File'))

server.R

getData <- reactive({
if(is.null(input$file1) && is.null(input$file2)) 
  {return(NULL)}
else {return(1)}
})

output$fileUploaded <- reactive({
return(!is.null(getData()))
})
outputOptions(output, 'fileUploaded', suspendWhenHidden=FALSE)

这只是另一种使用conditionalPaneloutputOptions的方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接