Shiny: Show buttons only after file has been uploaded

前端 未结 2 720
清歌不尽
清歌不尽 2021-02-05 17:24

I\'m experimenting with Shiny and I love it. I built a little application where students upload a csv file and then choose a dependent variables and independent variables and th

2条回答
  •  粉色の甜心
    2021-02-05 17:58

    This code worked for me

    ui.R

     # ui.R
    library(shiny)
    
    shinyUI(fluidPage(
      titlePanel("Multiple Linear Regression"),
      sidebarLayout(
        sidebarPanel(
          fileInput('file1', 'Choose CSV File',
                    accept=c('text/csv', 
                             'text/comma-separated-values,text/plain', 
                             '.csv')),
    
          tags$hr(),
          uiOutput("dependent"),
          uiOutput("independents"),
          tags$hr(),
          uiOutput('ui.action') # instead of conditionalPanel
        ),
        mainPanel(
          verbatimTextOutput('contents')
        )
      )
    ))
    

    server.R

    # server.R
    library(shiny)
    
    shinyServer(function(input, output) {
    
      filedata <- reactive({
        infile <- input$file1
        if (is.null(infile)){
          return(NULL)      
        }
        read.csv(infile$datapath)
      })
    
      output$dependent <- renderUI({
        df <- filedata()
        if (is.null(df)) return(NULL)
        items=names(df)
        names(items)=items
        selectInput("dependent","Select ONE variable as dependent variable from:",items)
      })
    
    
      output$independents <- renderUI({
        df <- filedata()
        if (is.null(df)) return(NULL)
        items=names(df)
        names(items)=items
        selectInput("independents","Select ONE or MANY independent variables from:",items,multiple=TRUE)
      })
    
    
      output$contents <- renderPrint({
        input$action
        isolate({   
          df <- filedata()
          if (is.null(df)) return(NULL)
          fmla <- as.formula(paste(input$dependent," ~ ",paste(input$independents,collapse="+")))
          summary(lm(fmla,data=df))
        })   
      })
    
    
      output$ui.action <- renderUI({
        if (is.null(input$file1)) return()
        actionButton("action", "Press after reading file and selecting variables")
      })
    
    }) 
    

提交回复
热议问题