Home > database >  Pass a variable from Server to UI
Pass a variable from Server to UI

Time:04-26

Please have a look at the snippet at the end of the email. I would like the second picker input to have a list of choices which is not the hard coded seq(100), but seq(nn), where nn is generated in the server part. How can I pass this value from the server to the user interface (UI)?

Many thanks

library(shiny)
library(shinyWidgets)


ui <- fluidPage(
          pickerInput("init_seed","Select the value of the random number seed",
                  choices=(c(1000,2000,3000)),
                  selected=c(1000),
                  options = list(`actions-box` = TRUE,
                                 `selected-text-format` = "count > 3"),multiple = F),
          pickerInput("2nd_choice","Select the value of the output random number",
                  choices=seq(100),
                  selected=c(10),
                  options = list(`actions-box` = TRUE,
                                 `selected-text-format` = "count > 3"),multiple = F)

)


server <- function(input, output) {
    nn <- reactive({
        set.seed(input$init.seed)
        round(runif(1,0,1000),0)
 })
}


shinyApp(ui = ui, server = server)
#> PhantomJS not found. You can install it with webshot::install_phantomjs(). If it is installed, please make sure the phantomjs executable can be found via the PATH variable.
<div style="width: 100% ; height: 400px ; text-align: center; box-sizing: border-box; -moz-box-sizing: border-box; -webkit-box-sizing: border-box;" >Shiny applications not supported in static R Markdown documents</div>

CodePudding user response:

As requested by OP in comments.

Note that I've corrected the typo in the nn reactive.

If the only use of nn is to generate the upper limit of the selection list, the reactive can be deleted and the limit generated within the observeEvent. I'm not sure that hard coding the random number seed inside the reactive (or the observeEvent) is a good idea.

library(shiny)
library(shinyWidgets)

ui <- fluidPage(
  pickerInput("init_seed","Select the value of the random number seed",
              choices=(c(1000,2000,3000)),
              selected=c(1000),
              options = list(`actions-box` = TRUE,
                             `selected-text-format` = "count > 3"),multiple = F),
  pickerInput("2nd_choice","Select the value of the output random number",
              choices=seq(100),
              selected=c(10),
              options = list(`actions-box` = TRUE,
                             `selected-text-format` = "count > 3"),multiple = F)
  
)

server <- function(input, output, session) {
  nn <- reactive({
    set.seed(input$init_seed)
    round(runif(1,0,1000),0)
  })
  
  observeEvent(nn(), {
    updatePickerInput(session, "2nd_choice", choices=seq(1:nn()))
  })
}

shinyApp(ui = ui, server = server)
  • Related