Creating dynamic UI components in Shiny
I was recently trying to implement some dynamic functionality in Shiny. The aim was to have a set number of UI elements load depending on a numeric value entered by the user, and then use the data input in these elements later in the app.
I found the following thread on SO by someone having the same issue. The first answer details how to create a series of UI elements dynamically; the following snippet shows a similar example that creates a series of numericInput
elements depending on the value entered in the drop down,
This is relatively simple, however the OP goes on to ask how to actually use the values within these elements. This is a bit tricky, as each element has to have a unique name, and accessing these named variables isn’t straightforward using the common Shiny syntax. I had a Google around, and found the following thread, where Joe Cheng himself (the original developer of Shiny) chipped in with an elegant solution. The following syntax allows you to access input variables named dynamically,
Using this, we can simply access our iteratively named variables by constructing the appropriate strings within this call. I do this for each of the numericInput
elements initialised above, and construct a table from the users input.
You can see this in action as a Shiny app here A gist of the complete app code is available here.
Enjoy Reading This Article?
Here are some more articles you might like to read next: