Timothy Shen Timothy Shen - 3 months ago 8
R Question

Call function and save return list in Shiny

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.

Answer

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)
Comments