Stophface Stophface - 1 month ago 15
R Question

Shiny variable overwriting

I am having something like

step <- 0

observeEvent(input$myInput, {
print(step)
if(!is.null(input$myInput) && step == 0 {
# do something
step <- 1
print(step)
} else if(!is.null(input$myInput) && step == 1) {
# do something
print("Been in second condition")
} else {
# do something else
}
})


When I execute my app and the
observeEvent
kicks in for the first time,
step
is as expected
0
and the first
if-condition
starts. At the end it sets
step <- 1
. The
print()
in there shows me that
step
is
1
. However, when the
observeEvent
kicks in the second time,
step
still is
0
. Thats what the
print
statements show. Why is that?

Answer

I think this is basically a scoping issue. Your handler expression - the stuff in observeEvent between the brackets, is treated as its own function. If you look at the code for observeEvent the handlerExpr argument is converted to a function via exprToFunction().

In your handler expression step is not defined, so it get the value 0 from outside the expression. Within the expression step is incremented to one, but that is only within that instance of the handlerExpr, that does not carry outside to change the original value of step to 1.

Comments