Search code examples
user-interfaceshinyuser-input

Shiny - create list of numeric inputs based on variable names loaded from a file


I would like to load a CSV file with inside a list of variable names such as

"var_A", "var_B", "var_C"

and create in the GUI a list of numeric inputs for each variable name. I guess I need to pass by uiOutput function but no idea to do that. here's a kinda draft of what I'm trying to do

ui <- bootstrapPage(
    fileInput('file1', 'Choose CSV File', accept=c('text/csv', 'text/comma-separated-values,text/plain', '.csv'))

    # list of numeric inputs
    #uiOutput("list_numeric_inputs")
   )

server <- function(input,output) {

  data_set <- reactive({
    inFile <- input$file1

    if (is.null(inFile))
      return(NULL)

    data_set<-read.csv(inFile$datapath, header=F)
  })

  # # list of numeric inputs
  # output$list_numeric_inputs <- renderUI({
  #   # If missing input, return to avoid error later in function
  #   if(is.null(input$data_set()))
  #     return()
  #   
  #   # Get the data set value for variable name
  #   for (i in 1:nrow(data_set)) {
  #     numericInput("...", paste0(data_set[i]), value = 0.)
  #   }
  # })

}

shinyApp(ui, server)

Solution

  • 1) Your example not working ( havent inputs for header=input$header,sep=input$sep, quote=input$quote)

    2)You havent input$dataset only data_set <- reactive

    3) So working one :

    library(shiny)
    ui <- bootstrapPage(
      fileInput('file1', 'Choose CSV File', accept=c('text/csv', 'text/comma-separated-values,text/plain', '.csv')),
    
      # list of numeric inputs
      uiOutput("list_numeric_inputs")
    )
    
    server <- function(input,output) {
    
      data_set <- reactive({
        inFile <- input$file1
    
        if (is.null(inFile))
          return(NULL)
    
        data_set<-read.csv(inFile$datapath,header = F)
      })
    
       # list of numeric inputs
       output$list_numeric_inputs <- renderUI({
         # If missing input, return to avoid error later in function
         if(is.null(data_set()))
           return()
    
       # Get the data set value for variable name
         lapply(data_set(),function(i){
           numericInput(paste0(i,"_ID"), i, value = 0.)
         }
       ) 
       })
    
    }
    
    shinyApp(ui, server)