Jean V. Adams Jean V. Adams - 1 month ago 15
R Question

Repeating reactive output in Shiny

I want to display the same reactive text output at multiple locations in an R Shiny app. Here is a simple example (in a single R markdown document):

---
output: html_document
runtime: shiny
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo=FALSE)
```

```{r}
output$text1 <- renderText({
paste("Selected letter:", input$var)
})

fluidPage(
fluidRow(
selectInput("var", label="Choose a letter", choices=letters[1:4], selected="b")
),
fluidRow(
textOutput("text1")
),
fluidRow(
textOutput("text1")
)
)
```


This code works fine if I delete the middle
fluidRow(textOutput("text1")),
with the app showing the initial text Selected letter: and the reactive input b once. But, if I leave that piece of code in, it doesn't display the same text twice, as I expected it would. Instead, the app shows the initial text Selected letter: only once and the reactive input b not at all.




For completeness, I am adding example code (for the second chunk) that provides a work around.

n <- 2
for(i in seq(n)) {
output[[paste0("text",i )]] <- renderText(paste("Selected letter:", input$var))
}

fluidPage(
fluidRow(
selectInput("var", label = "Choose a letter",
choices = letters[1:4], selected = "b")
),
fluidRow(
textOutput("text1")
),
fluidRow(
textOutput("text2")
)
)

Answer

Shiny Inputs/Outputs must have unique IDs. Quote from http://shiny.rstudio.com/articles/modules.html

Input and output IDs in Shiny apps share a global namespace, meaning, each ID must be unique across the entire app. If you’re using functions to generate UI, and those functions generate inputs and outputs, then you need to ensure that none of the IDs collide.

Shiny Modules and Namespaces provide a way to organize your code and avoid name collisions.

Comments