4
votes

I want to build an R shiny app that has a dynamic input that asks the user for a numeric input and then based on that input generates 4 more input fields. Here is what I have in mind.

library(shiny)

# Define UI for random distribution application 
shinyUI(fluidPage(

  # Application title
  titlePanel("Calcs"),

  # Sidebar with controls to select the random distribution type
  # and number of observations to generate. Note the use of the
  # br() element to introduce extra vertical spacing
  sidebarLayout(
    sidebarPanel(
     numericInput("dorr", "How many inputs do you want",4),
     i = i+1
     while(input$dorr<i){
      numericInput("S", "Number of simulations to run:", 10)
      i=i+1
     }
     numericInput("S", "Number of simulations to run:", 10),
     actionButton(inputId = "submit_loc",label = "Run the Simulation")
     ),


     mainPanel(

  )
)))

I know the above code doesn't work, but it is my rationale. I know that Shiny has conditional statements but I can't seem to find one that allows me to generate a pre-specified number of additional fields. Is this even possible?

1
You need to use renderUI in the server code. See this page shiny.rstudio.com/articles/dynamic-ui.html for some examplesXiongbing Jin
@warmoverflow I am already aware of that, but I don't understand how to use it to dynamically create a pre-specified number of inputs.RustyStatistician

1 Answers

4
votes

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)