1
votes

I am trying to execute a function inside observeEvent()

I have

  • two predefined functions: calculate_value() and create_my_plot()
  • one input stored as reactive variable: myreactive()
  • one dataset a read from file. File is chosen according to input value.
  • a is processed with calculate_value() and passed to create_my_plot()

it goes like this:

myreactive<-reactive({input$myinput})
observeEvent(input$clicks,
{
 filename<-paste(myreactive(),".csv")
 a<-read.csv(filename)
 x<-calculate_value(a,b=myreactive())
 output$myplot<-renderPlot(
                   create_my_plot(x,myreactive())
 })

Whenever I click action button this event is activated and new plot plotted. But also whenever myreactive() is changed this plot is replotted. This is good. But there is a problem with the replotted plot: it still uses "old" version of "x"

I need the function calculate_value() to be reacalculated whenever myreactive() is changed. It doesn't happen

I tried already usinig

x<-reactive({ calculate_value(a,b=myreactive()) })

but then nothing happens. Namely the function is not executed at all and x is left as null. For me this is unacceptable because "myreactive()" is changing the dataset and the description of the plot and if the plot is not re-plotted accordingly it is simply wrong.

It would be enough to delete the plot entirely if myreactive() changes but I actually would like to know what is going on and why I can't have calculate_value() re-do calculations each time while create_my_plot() can do it.

1
could you upload your code for the app to a gist (or attach it at the end of your question)? It would be possible to inspect all your code and possibly try the app, running runGist(key). - Thomas K

1 Answers

3
votes

In my case, when I use observerEvent(), all things that introduce in this method change when some value changes. Shiny is an framework which utilizes reactive programming. In whatever case, you would use reactive(), to reutilize code and to have a clean code. If you use this variable and the value change, the value will change in all locations.

A solution to your problem, it could be to use observe() inside observerEvent(). Indeed, each time that the values of the intern code changes, the observe() will execute everything inside in it.

You can see this example, and try with it:

  testReactive<-reactive({as.numeric(input$numberTest)})

  observeEvent(input$bTest,{
    observe({   
                 x<-10+testReactive()
                 output$testing<-renderText(print(x))

            }) #Closed observe
  }) #Closed observeEvent