Reputation: 57176
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.
Upvotes: 1
Views: 5198
Reputation: 919
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.
Upvotes: 4