0

I am trying to call a function in server.R and save the returned list into global environment, which the function is called by an action button. Then I will use that list to run another function which is triggered by another button, based on the list, to plot a graph. Here's a simple sample code:

shinyServer(function(input, output) {

  v <- reactiveValues()

  observeEvent(input$button1, {
    v$button1 = TRUE
  })

  savedlist <<- reactive({
    if (v$button1){
      return(savedlist <- f1(10)
    }
  })

 output$plot <- renderPlot({
   f2(savedlist)
 })

})

where

f1 <- function(x){
  savedlist = list(xdata = 1:x, ydata = x:1)
  names(savedlist) = c("xdata", "ydata")
  return(savedlist)
}

and

f2 <- function(x){
  attach(savedlist)
  plot(xdata, ydata)
}

but I can't get it to work...

Thanks.

Timothy Shen
  • 73
  • 1
  • 8
  • Try `observe({if (v$button1){ savedlist <<- f1(10) }})` – Batanichek Aug 26 '16 at 06:59
  • Thank you for reply. It gives me error: `Warning: Error in if: argument is of length zero` – Timothy Shen Aug 26 '16 at 07:44
  • Try add default value `v <- reactiveValues(button1=FALSE)` – Batanichek Aug 26 '16 at 07:47
  • Thank you again. There is no error now but when I click the button, nothing happens. It takes about a minute to run the function. How do I know it's running? I have implemented [this](http://stackoverflow.com/questions/17325521/r-shiny-display-loading-message-while-function-is-running) (the loading... signal) and when I press the button it is not loading. – Timothy Shen Aug 26 '16 at 07:57

1 Answers1

1

Try this

library(shiny)
ui=shinyUI(fluidPage(

  actionButton("button1","button1"),
  plotOutput("plot")

))
f1 <- function(x){
  savedlist = list(xdata = 1:x, ydata = x:1)
  names(savedlist) = c("xdata", "ydata")
  return(savedlist)
}
f2 <- function(x){ # change a bit to use x as argument
  plot(x$xdata, x$ydata)
}

server=shinyServer(function(input, output) {

  v <- reactiveValues(button1=FALSE)

  observeEvent(input$button1, {
    v$button1 = TRUE
  })

  observe({
    if (v$button1){
      savedlist <<- f1(10)
    }
  })

      output$plot <- renderPlot({
        if(v$button1){# plot only after button because before list dont exist
        f2(savedlist)
        }
      })

})

shinyApp(ui,server)
Batanichek
  • 7,761
  • 31
  • 49