Home > Software engineering >  R/Shiny: Populate SelectInput Options using Headers From Uploaded File
R/Shiny: Populate SelectInput Options using Headers From Uploaded File

Time:10-17

I'm trying to build a page using R Shiny that has:

  • A File Widget for uploading CSV files

  • A SelectInput component

I'd like to use these as follows:

  • Upon uploading a valid CSV file, populate the SelectInput whose options are the headers from the CSV file, the first header being the default selected

I've tried various forms of observe() and observeEvent() so far, but have had no success in getting this even close. Any suggestions you may have would be great.

CodePudding user response:

Here's an option -

library(shiny)

#Sample data
#write.csv(mtcars, 'data.csv', row.names = FALSE)

ui <- fluidPage(
  fileInput('file', 'Upload csv file'),
  uiOutput('dropdown')
)

server <- function(input, output) {
  data <- reactive({
    req(input$file)
    read.csv(input$file$datapath)
  })
  
  output$dropdown <- renderUI({
    req(data())
    selectInput('cols', 'Select Column', names(data()))
  })
}


shinyApp(ui, server)

enter image description here

  • Related