R Shiny Dynamic Input

Solution 1:

See a working example below

library(shiny)

ui <- shinyUI(fluidPage(
  titlePanel("Old Faithful Geyser Data"),

  sidebarLayout(
    sidebarPanel(
      numericInput("numInputs", "How many inputs do you want", 4),
      # place to hold dynamic inputs
      uiOutput("inputGroup")
    ),
    # this is just a demo to show the input values
    mainPanel(textOutput("inputValues"))
  )
))

# Define server logic required to draw a histogram
server <- shinyServer(function(input, output) {
  # observe changes in "numInputs", and create corresponding number of inputs
  observeEvent(input$numInputs, {
    output$inputGroup = renderUI({
      input_list <- lapply(1:input$numInputs, function(i) {
        # for each dynamically generated input, give a different name
        inputName <- paste("input", i, sep = "")
        numericInput(inputName, inputName, 1)
      })
      do.call(tagList, input_list)
    })
  })

  # this is just a demo to display all the input values
  output$inputValues <- renderText({
    paste(lapply(1:input$numInputs, function(i) {
      inputName <- paste("input", i, sep = "")
      input[[inputName]]
    }))
  })

})

# Run the application
shinyApp(ui = ui, server = server)