-
-
Save motin/0d0ed0d98fb423dbcb95c2760cda3a30 to your computer and use it in GitHub Desktop.
Dynamically append arbitrary number of inputs (Shiny)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(shiny) | |
shinyServer(function(input, output) { | |
output$allInputs <- renderUI({ | |
# Get value of button, which represents number of times pressed (i.e. number of inputs added) | |
inputsToShow <- input$appendInput | |
# Return if button not pressed yet | |
if(is.null(inputsToShow) || inputsToShow < 1) return() | |
# Initialize list of inputs | |
inputTagList <- tagList() | |
# Populate the list of inputs | |
lapply(1:inputsToShow,function(i){ | |
# Define unique input id and label | |
newInputId <- paste0("input", i) | |
newInputLabel <- paste("Input", i) | |
# Prevent dynamic inputs from resetting | |
newInputValue <- "Option 1" | |
if (newInputId %in% names(input)) { | |
newInputValue <- input[[newInputId]] | |
} | |
# Define new input | |
newInput <- selectInput(newInputId, newInputLabel, c("Option 1", "Option 2", "Option 3"), selected=newInputValue) | |
# Append new input to list of existing inputs | |
inputTagList <<- tagAppendChild(inputTagList, newInput) | |
}) | |
# Return updated list of inputs | |
inputTagList | |
}) | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(shiny) | |
shinyUI(pageWithSidebar( | |
# Application title | |
headerPanel("Dynamically append arbitrary number of inputs"), | |
# Sidebar with a slider input for number of bins | |
sidebarPanel( | |
uiOutput("allInputs"), | |
actionButton("appendInput", "Append Input") | |
), | |
# Show a plot of the generated distribution | |
mainPanel( | |
p("This shows how to add an arbitrary number of inputs | |
without resetting the values of existing inputs each time a new input is added. | |
For example, add a new input, set the new input's value to Option 2, then add | |
another input. Note that the value of the first input does not reset to Option 1.") | |
) | |
)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Have you tried to put this inside of a shiny module? the tagAppendChild blows up and throws an error: Error in as.vector: cannot coerce type 'closure' to vector of type 'character'
I cannot figure out a way around it.