Search code examples
rshinyselectinput

How can I use the column names of a csv file as input selection?


I created a Shiny App, which accepts Excel and csv files as input. It furthermore, should forecast a metric which can be found in the uploaded file. To be able to define the right column in the file, the user should be able to select the column which should be forecasted. This is why I want to have a select input area, where all column names of the file are displayed. But I don't find the right solution.

In the following my app so far:

ui:

 ui <- fluidPage(  

  #definition which file input is allowed
  fileInput(
    'file',
     label = h4("Welche Datei soll hochgeladen werden?"),
     multiple= FALSE,
     accept = c(
      'text/csv',
      'text/comma-separated-values,text/plain',
      '.csv',
      '.xlsx'
   )
  ),

server:

server <- function(input, output) {

#read data 
data <- reactive({

  validate(need(input$file, ""))
  infile <- input$file

  if (input$type == "1") {
   read.csv(infile$datapath,
           header = input$header,
           sep = input$sep,
           stringsAsFactors = FALSE)
  } else {
  read_xlsx(infile$datapath)
  }    

})

And I thought about something like this in server, but could not finally solve the problem:

names <- reactive({
 df <- data()
 if (is.null(df)) return(NULL)

 items=names(df)
 names(items)=items

 return(names(items))

})

Thanks for any help!


Solution

  • Inside UI, you should add:

    selectInput("columnid","Column to forecast",choices=c())

    your server should start like this: server <- function(session,input, output) {

    and inside the server, after the else inside your reactive you can add:

    updateSelectInput(session,"columnid",choices=colnames(mydata))

    remember to call "mydata" the data that was read, and to return it, like this:

    data <- reactive({
    
      validate(need(input$file, ""))
      infile <- input$file
    
      if (input$type == "1") {
       mydata=read.csv(infile$datapath,
               header = input$header,
               sep = input$sep,
               stringsAsFactors = FALSE)
      } else {
       mydata=read_xlsx(infile$datapath)
      }
      updateSelectInput(session,"columnid",choices=colnames(mydata))
    return(mydata)
    })