manofbear
manofbear

Reputation: 111

Display number of columns according to user-input value

I have five columns, each of which has numericInputs. I also have a selectInput, from which the user can select an integer between 1 and 5. If the user picks n from the selectInput, I would like to display only the first n columns.

Right now, I only have a static version showing all 5 columns:

ui <- fluidPage(

  fluidRow(

column([col1 stuff]), 

...

column([col5 stuff])

))

Upvotes: 0

Views: 77

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388817

You can use lapply to create inputs dynamically.

library(shiny)

df <- mtcars[1:5, 1:5]

ui <- fluidPage(
  h3('Dynamic Input Selection'),
  selectInput("col", "Choose col number", choices = seq_along(df)),
  br(), br(),
  uiOutput("num_input")
)

server <- function(input, output) {
  output$num_input <- renderUI({
    lapply(seq_len(input$col), function(x) 
           numericInput(paste0('inp', x), paste0('Input ', x), 1, 1, 10))
  })
}

shinyApp(ui, server)

enter image description here

Upvotes: 1

lz100
lz100

Reputation: 7330

how about this

library(shiny)

ui <- fluidPage(
    selectizeInput("n_col", "Choose col number", choices = 1:5, selected = 2),
    fluidRow(
        uiOutput("col_out")
    )  
)

server <- function(input, output, session) {
    # define column content 
    cols <- list(
        column(
            2, 
            p("This is col 1"),
            numericInput("nu1", "nu1", value = 1, min = 1, max = 100)
        ),
        column(
            2, 
            p("This is col 2"),
            numericInput("nu2", "nu2", value = 1, min = 1, max = 100)
        ),
        column(
            2, 
            p("This is col 3"),
            numericInput("nu3", "nu3", value = 1, min = 1, max = 100)
        ),
        column(
            2, 
            p("This is col 4"),
            numericInput("nu4", "nu4", value = 1, min = 1, max = 100)
        ),
        column(
            2, 
            p("This is col 5"),
            numericInput("nu5", "nu5", value = 1, min = 1, max = 100)
        )
    )
    output$col_out <- renderUI(
        cols[1:as.numeric(input$n_col)]
    )
}

shinyApp(ui, server)

enter image description here

Upvotes: 1

Related Questions