Optimization of conditionalPanel() in R Shiny app

Viewed 31

I'm developing a shiny web app and I have an issue with a conditionalPanel(). Well, it's not a problem because the app works fine. However, I'm not happy with the code itself, since is quite repetitive. I've been reading a lot around here and couldn't find some answer to solve what I'm looking for (If I'm missing an entrance that works on this please notice me), so here it goes.

I have a conditionalPanel that shows one to four numeric inputs based on a condition as the next code shows.

library(shiny)
library(shinythemes)

ui <- fluidPage(

    theme = shinytheme('darkly'),
    
    titlePanel("Some nice title"),

    sidebarPanel(
        
        selectInput("BaseType", "Number of values:", c(seq(1,4))),

        conditionalPanel(
            condition = "input.BaseType == 1",
            numericInput("value1", "First value:", value = 0, step = 0.01)),

        conditionalPanel(
            condition = "input.BaseType == 2",
            numericInput("value1", "First value:", value = 0, step = 0.01),
            numericInput("value2", "Second value:", value = 0, step = 0.01)),
        
        conditionalPanel(
            condition = "input.BaseType == 3",
            numericInput("value1", "First value:", value = 0, step = 0.01),
            numericInput("value2", "Second value:", value = 0, step = 0.01),
            numericInput("value3", "Third value:", value = 0, step = 0.01)),
        
        conditionalPanel(
            condition = "input.BaseType == 4",
            numericInput("value1", "First value:", value = 0, step = 0.01),
            numericInput("value2", "Second value:", value = 0, step = 0.01),
            numericInput("value3", "Third value:", value = 0, step = 0.01),
            numericInput("value4", "Fourth value:", value = 0, step = 0.01))
    )
)

server <- function(input, output) {
}

shinyApp(ui = ui, server = server)

This isn't the whole app, It's just a summarized example of my app. Precisely I'm asking if is there a way to not repeat in every conditionalPanel() the same lines (I'm quite new at R and specially in shiny). If someone need some context, the app is about a titration curves generator and this part is for weak acids and bases, and based on how many pKa or pKb it has, the amount of inputs that I want.

1 Answers

You can dynamically generate numericInput using lapply in server which will avoid repeating the code for possible input.

library(shiny)
library(shinythemes)

ui <- fluidPage(
  theme = shinytheme('darkly'),
  titlePanel("Some nice title"),
  sidebarPanel(
    selectInput("BaseType", "Number of values:", c(seq(1,4))),
    uiOutput('value')
))

server <- function(input, output) {
  output$value <- renderUI({
    lapply(seq_len(input$BaseType), function(x) {
      numericInput(paste0('value', x), sprintf("value %d :", x), 
                   value = 0, step = 0.01)
    })
  })
}

shinyApp(ui = ui, server = server)
Related