简体   繁体   中英

Shiny observer - how to use observer to update global variables?

How can I update the global variable using observer?

I have an empty species on start:

speciesChoices <- c()

But I want to add values into it when something has changed on the ui, so it becomes:

speciesChoices <- c(
    'PM2.5' = 'particles'
)

Is it possible?

My code so far...

ui.r:

speciesOptions <- selectInput(
    inputId = "species",
    label = "Species:",
    choices = c(
        # 'PM2.5' = 'particles',
        # 'Humidity %' = 'humidity'
    )
)

server.r:

speciesChoices <- c() # global variable

# Define server logic required to draw a histogram
shinyServer(function(input, output, session) {

   observe({
        key <- input$streams1

        stream <- fromJSON(paste(server, "/output/stream?public_key=", key, sep=""),flatten=TRUE)
        species <- as.data.frame(stream$species)

        # Set choices of title and code for select input.
        speciesChoices <- setNames(species$code_name, species$public_name)

        updateSelectInput(session, "species", choices = speciesChoices)
    })

})

It only update the input on the ui but not the speciesChoices on the server.

any ideas?

Use something like speciesChoices <<- setNames(input$species$code_name, input$species$public_name) . You need both the super-assign operator <<- to change a global variable, and you need to use input$_id_ to refer to inputs set in the ui.

Side note: I'm not sure what your endgame is here, but make sure that you actually want to be using an observer and not a reactive. For an idea of the difference between these, see Joe Cheng's slides from useR2016 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM