Arun
Arun

Reputation: 51

Passing parameters into Shiny server

I've built a shiny application that allows users to import genetic data, and visualize it. I want users to be able to pass in the path to their data as a parameter into the server. Is there any way to do this? The path would simply be a string that is passed into the server function.

The reason I want this passed in as a parameter, and not some other solution, is I am currently creating an R package of this application, and I will have a function within the package that will launch the application.

This function will look something like this:

runMyApp <- function() {
  shiny::runApp(system.file("myapp", package="mypackage"))
}

Is there any way for me to pass a parameter into this runApp function, which in turn is passed into the server?

Thank you!

Upvotes: 2

Views: 1794

Answers (1)

Alexis
Alexis

Reputation: 5069

I haven't tested this extensively, but it seems to work.

Define shiny's ui and server as desired in inst/myapp.R (I assume the variables have these names), but do not call shinyApp. Then in your package you can define a function like:

launch_app(param, ...) {
  file_path <- system.file("myapp.R", package = "mypackage")
  if (!nzchar(file_path)) stop("Shiny app not found")
  ui <- server <- NULL # avoid NOTE about undefined globals
  source(file_path, local = TRUE)
  server_env <- environment(server)

  # Here you add any variables that your server can find
  server_env$test_param <- "test"
  server_env$param <- param

  app <- shiny::shinyApp(ui, server)
  shiny::runApp(app, ...)
}

Then any function inside your server should be able to see param and test_param and use it.

This also has the added advantage that all functions in your server will be able to use any unexported function from your package.

Here's an example of how I do it in my package, with the launching function defined here.

Upvotes: 9

Related Questions