How to make a for loop reactive in shiny server?

1,962 views
Skip to first unread message

umair durrani

unread,
Sep 3, 2015, 12:11:52 AM9/3/15
to Shiny - Web Framework for R
I am using assign in for loop to create new variables that I want to use in more than one outputs in shiny ui. Following is a sample code:

library(shiny)
ui
<- fluidPage(

  mainPanel
(fluidRow(textOutput("a")),
            fluidRow
(textOutput("b")))
)
server
<- function(input, output) {

  m
<- reactive({1:5})

  output$a
<- renderPrint({

   
for (i in 1:length(m())){
      assign
(paste0("h",i), "u")
     
}

    list
(h1,h2)
 
})

  output$b
<- renderPrint({

   list
(h1,h2)
 
})
}
shinyApp
(ui = ui, server = server)

How can I make for loop reactive and put it outside `output` function so that all `output` functions could access the h variables?

Note: question posted on stackoverflow as well.

David Zornek

unread,
Sep 4, 2015, 11:40:08 AM9/4/15
to Shiny - Web Framework for R
If you mean, make the code react to a user input for number of variables, then all you need to do is create an input widget for the user to select the number of variables. Either a sliderInput or numericInput or selectInput will do.

Then, you won't need m <- reactive({1:5}). You can just have your loop reference the input like this: for(i in 1:input$number){ your code }.

As for making the variables accessible by other functions, you should be able to use the envir argument of assign() to scope it to a different environment that's more accessible. Try envir = globalnenv().

Joe Cheng

unread,
Sep 4, 2015, 12:29:57 PM9/4/15
to David Zornek, Shiny - Web Framework for R
When h1/h2 change, do you want output$b to update? If so, these are not normal variables but reactive values.

server <- function(input, output) {

  m <- reactive({1:5})
  v <- reactiveValues()

  output$a <- renderPrint({

    for (i in 1:length(m())){
      v[[paste0("h",i)]] <- "u"
    }

    list(v$h1,v$h2)
  })

  output$b <- renderPrint({

   list(v$h1,v$h2)
  })
}
shinyApp(ui = ui, server = server)
--
You received this message because you are subscribed to the Google Groups "Shiny - Web Framework for R" group.
To unsubscribe from this group and stop receiving emails from it, send an email to shiny-discus...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/shiny-discuss/40144f80-ab81-4e04-88b0-7913dd6d6073%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages