2017-05-25 63 views
0

我有下面的代码,它允许接受csv文件 - >运行R代码 - >显示 - >下载输出。仅在主面板中显示输出时在Shiny 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) 
     } 
    ) 
    }) 

}) 

谢谢!

回答

2

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

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

,并在UI方面,你替换下载按钮:

uiOutput("download") 
+0

谢谢!这很好用! – MysticRenge

1

shiny网络应用程序中隐藏/显示对象的简单方法是使用Dean Attali的令人惊叹的shinyjs包。这个软件包是widley的文档,你可以在Dean的博客上找到一整套关于this page的工作示例。

1

替代解决方案上面,你也可以使用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另一种方法。