Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simultaneously access environment from two R sessions

Tags:

Is it technically possible in R?

I would like to run a shiny instance with prepared R6 object (environment class), use its methods - mostly read only.
While at the same time as shiny app running I would like to call other methods of my R6 - read/write.
Shiny R session could be a host for my R6 object while the second session would be called from scheduled R script / interactively from R console.
Currently what I think I can do is to source R script directly from shiny under a button, but this limits interactivity.

like image 793
jangorecki Avatar asked Jul 08 '15 18:07

jangorecki


1 Answers

This article describes the scoping rules for Shiny apps and how to define global data with variously packaged code. Below is my example of a global variable holding data accessible to multiple sessions.

Run this app, then open a second tab/window in your browser and point it at the same connection. You can click the +1 button in one session to increment the shared max and local count. In the other session, you will not see any change until something triggers shiny to re-check the shared data, but clicking the +1 button there will update the local count, but also trigger update of the shared max data value. You can click the +1 button there several times until you have a new max, then go back to the first window and you can see the max is visible there too, once you click the +1 button to trigger an update. This works for multiple windows.

You have to do something to make a session check the data again to update. I didn't work too hard to make this happen without side effects. There should be some way to do a "refresh" based on whatever trigger you want. You can even use a timed poll to keep data in sync, like this example does with files.

The one caveat to this example is I have only tried with a local RStudio shiny server implementation. I don't know that it works this way on a real server. If it does not, please comment to that effect! It will probably not work this way on shinyapps.io or with any kind of cloud/load-balancing in general as you can't guarantee that two sessions share an app instance on one machine.

library(shiny)

globalMax <- 0

app <- shinyApp(
   ui= pageWithSidebar(
      headerPanel("Shared data demo"),
      sidebarPanel(
         actionButton("plusButton", "+1")
      ),
      mainPanel(
         verbatimTextOutput("sharedMax")
      )
   ),
   server= function(input,output){
      observe({
         if (input$plusButton > globalMax) {
            globalMax <<- input$plusButton
         }
      })
      output$sharedMax <- renderText({
         paste0( "Shared max value: ",  globalMax, "\n",
                 "Local value: ",  input$plusButton)
      })
   }
)

runApp(app)
like image 169
Stuart R. Jefferys Avatar answered Oct 20 '22 19:10

Stuart R. Jefferys