selectInput based on columns of uploading csv file

I am trying to build a shiny app where I can upload a csv file and based on the column names, from selectInput - app shows basic statistic (graphs, descriptive statistic-average, sd, var .... and some statistical tests). There is no problem with datasets, which are already in the app. Also no problem with statistics. Problem is how to make working selectInput with the names of columns from new upload csv file.

Here is my light version of code:

UI:

library(shiny)
shinyUI(fluidPage(
    titlePanel("xxx"),

    sidebarLayout(
        sidebarPanel(
            fileInput("csvFile", "Drag cars.csv over here!"),
            selectInput("var", "choose variable:", choices= names(data()))
        ),

        mainPanel(
            textOutput("average"),
            plotOutput("plot")
        )
    )
))

SERVER:

shinyServer(function(input, output, session) {
    data <- reactive({
        file1 <- input$csvFile
        if (is.null(file1)) { 
            return() 
        } 
        data = read.csv(file=file1$datapath)
        data
    })
    output$average <- renderText({
        paste("average is: ", mean(data()[,input$var]))
    })
    output$plot <- renderPlot({
        boxplot(data()[,input$var])
    })
})

Upvotes: 1

Views: 1337

Answers (2)

theairbend3r
theairbend3r

Reputation: 799

You can also use observe in server. observe does not return anything. Unlike reactive, it responds immediately (and not lazily). It's best used for ip/op operations.

observe({
  updateSelectInput(
    session,
    "var",
    choices = names(data())
  )
)}

Upvotes: 3

Nirmal
Nirmal

Reputation: 687

You will need to use uiOutput() and renderUI() functions.

library(shiny)

ui <- fluidPage(
  titlePanel("xxx"),

  sidebarLayout(
    sidebarPanel(
      fileInput("csvFile", "Drag cars.csv over here!"),
      uiOutput("var_ui")
    ),

    mainPanel(
      textOutput("average"),
      plotOutput("plot")
    )
  )
)

server <- function(input, output, session) {
  data <- reactive({
    file1 <- input$csvFile
    if (is.null(file1)) { 
      return() 
    } 
    data = read.csv(file=file1$datapath)
    data
  })
  output$average <- renderText({
    paste("average is: ", mean(data()[,input$var]))
  })
  output$plot <- renderPlot({
    boxplot(data()[,input$var])
  })

  output$var_ui <- renderUI({
    selectInput("var", "choose variable:", choices= names(data()))
  })
}

shinyApp(ui, server)

Upvotes: 3

Related Questions