shiny: use the same function to render a table and a plot without calling twice the function?

Hello all,

It is a bit tricky to explain but let's give it a try.

Some of my functions are of the following type:

Example_Function <- function (...) {
Table = ...
print(ggplot)
return(Table)
}

My shiny server.R have the following:

output$table <- renderTable({
isolate(inputs)
Table = Example_Function(inputs)
Table
})

output$plot <- renderPlot({
Example_Function(inputs)
})

It works but I would like to avoid calling 2 times the function as it takes useless time.

I cannot really use a list with the Table and the ggplot in it as this 'Example_Function' is used in many other functions, do.call(Example_Function, ...) etc.

Thanks for your help,

Regards,

Maxime

Hi,

There are several ways to do this in Shiny. The one closest to your structure would be this:

library(shiny)
library(ggplot2)

ui <- fluidPage(
  
  sidebarPanel(
    actionButton("myButton", "click")
    ),
  
  mainPanel(
    plotOutput("myPlot"),
    tableOutput("myTable")
  )
)

server <- function(input, output, session) {
  
  myPlot = reactiveVal()
  
  myData = reactive({
    input$myButton
    data = data.frame(x = 1:10, y = runif(10))
    myPlot(ggplot(data, aes(x = x, y = y)) + geom_point())
    data
  })
  
  output$myPlot = renderPlot({
    myPlot()
  })
  
  output$myTable = renderTable({
    myData()
  })
}

shinyApp(ui, server)

But you can also do this:

library(shiny)
library(ggplot2)

ui <- fluidPage(
  
  sidebarPanel(
    actionButton("myButton", "click")
    ),
  
  mainPanel(
    plotOutput("myPlot"),
    tableOutput("myTable")
  )
)

server <- function(input, output, session) {
  
  myPlot = reactiveVal()
  myData = reactiveVal()
  
  observeEvent(input$myButton, {
    data = data.frame(x = 1:10, y = runif(10))
    myData(data)
    myPlot(ggplot(data, aes(x = x, y = y)) + geom_point())
  }, ignoreNULL = F)
  
  output$myPlot = renderPlot({
    myPlot()
  })
  
  output$myTable = renderTable({
    myData()
  })
}

shinyApp(ui, server)

It all depends on what triggers the code (I choose a button) and what the structure of your reactive environment is.

Hope this helps,
PJ

Hi PJ,

I can't apply it directly to my case but it does help me to progress and will certainly be useful in the very near future!

Thanks a lot!

Maxime

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.