Search code examples
rshinyrstudioworkspacescoping

Pass only specific variables to a shiny app when building a package


I'm building a package which includes my shiny app.

To do this, I build a wrapper around my "shiny::runApp" call, but unfortunatly the shiny app uses the global workspace variables. I want the wraper function to use the variables i give to the function (and error if not supplemented) and use them for shiny. Here for example, it need x,y and z (which has a default value):

Shiny_wrapper <- function(x,y,z=TRUE){
    shiny::runApp(appDir = system.file("shinyApp", package = "WebFlood"))
}

I worked around it by assigning the variables to the global workspace, but I don't think this is the right approach:

Shiny_wrapper <- function(x,y,z=TRUE){
    x<<-x
    y<<-y
    z<<-z
    shiny::runApp(appDir = system.file("shinyApp", package = "WebFlood"))
}

How do I get my shiny to use the variables I pass to the wrapper?


Solution

  • You can define an environment in your package, and use it to pass some variables.

    PKGENVIR <- new.env(parent=emptyenv()) 
    
    #' @export
    Shiny_wrapper <- function(x,y,z=TRUE){
        PKGENVIR$x <- x
        PKGENVIR$y <- y
        PKGENVIR$z <- z
        shiny::runApp(appDir = system.file("shinyApp", package = "WebFlood"))
    }
    

    And then in the shiny app (in global.R or server.R):

    x <- WebFlood:::PKGENVIR$x