繁体   English   中英

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

[英]Display download button in Shiny R only when output appears in Main Panel

我有下面的代码,它允许接受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)
      }
    )
  })

})

谢谢!

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

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

在ui端,您将下载按钮替换为:

uiOutput("download")

shiny Web应用程序中隐藏/显示对象的一种简单方法是使用Dean Attali提供的惊人的Shinyjs包。 该软件包已记录在widley中,您可以在Dean的博客上的本页上找到完整的工作示例集。

除了上述解决方案之外,您还可以如下使用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另一种方法。

您也可以使用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) {}
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM