0

I'm trying to generate multiple reactive variables (#12) using a for loop. The initial values for the variables are indicated by the user input in the app. Thus the variables must be reactive and related to the user input. In the loop I want to simply add one each time the loop runs... (sort of like a counter).

The app is way more complicated, but I just need to know how to use for loop and reactive values together. So the example above is just a simplified version to learn the syntax and structure

Note that the code below doesn't run! I just included it to show how I want the app look like... or I think it should!

Thank you so much for your help guys!!!

ui <- fluidPage(
  numericInput("initial", "Enter the initial value here", value = 0),
  verbatimTextOutput("text1")
  verbatimTextOutput("text2")
)

server <- function(input, output, session) {
  counter <- reactiveValues (
    count1 = input$initial,
    count2 = input$initial
  )

  for (i in 1:10) {
    counter$count1 <- counter$count1 + 1
    counter$count2 <- counter$count2 + 2
  }

  output$text1 <- renderPrint(counter$count1)
  output$text2 <- renderPrint(counter$count2)
}

shinyApp(ui = ui, server = server)

1 Answers1

0

Your for loop is not producing multiple reactive values, it only updates the values in counter. If you need to add more elements to counter in a for loop you can do it using the double square bracket [[]] operator. Something like:

for (i in 1:10) {
  counter$[[paste0("count",i)]] <- i
}
Geovany
  • 5,389
  • 21
  • 37