dkro
dkro

Reputation: 213

R Shiny Randomly Generated Radio Button Choices

I'm creating a survey in Shiny where I want the choices as represented by radio buttons to be randomly drawn. See sample code below:

library(shiny)

choices<-c("a","b","c","d","e")
x1<-sample(choices,2)
x2<-sample(choices,2)

ui<-fluidPage(
     radioButtons("q1","Which do you prefer?", choices=c(x1,"No Preference"),selected=""),
     radioButtons("q2","Which do you prefer?", choices=c(x2,"No Preference"),selected="")),

server <- function(input, output) {
# Not important
})
shinyApp(ui = ui, server = server)

When I run the app locally a different set of choices will be selected each time I run the app (as intended). But once I publish to shinyapps.io the choices are the same each time (as in x1 is the same each time I run the app). How can I make so that each time the app opens a new sample is taken from the choice set?

Upvotes: 0

Views: 176

Answers (1)

Ian Campbell
Ian Campbell

Reputation: 24770

As you may know, Shiny server implements caching to improve system utilization. The problem you are having is the x1 variable is being sampled and cached between users.

The way around this problem is to sample choices into a reactiveValue and then dynamically update the radio buttons when the page loads.

Alternatively, you might try using this approach:

ui <- function(req) {
  fluidPage(
   x1<-sample(choices,2)
   x2<-sample(choices,2)
   radioButtons("q1","Which do you prefer?", choices=c(x1,"No Preference"),selected=""),
   radioButtons("q2","Which do you prefer?", choices=c(x2,"No Preference"),selected=""))
   ...
  )
}

Upvotes: 1

Related Questions