2

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!

1
  • There is a discussion about this in the shiny issues page. The solution there is to save the parameters in the global environment, Commented Jul 10, 2017 at 10:50

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

3 Comments

With this solution, does runApp need to be inside launch_app? Or could launch_app (renamed appropriately) return app to a calling script that then calls runApp on it?
And why hasn't this answer been chosen or upvoted? It seems less ugly than the ones recommended at the issues link in the comment to the original question.
You can certainly adapt the function as you desire, the key really is passing local=TRUE to source. I'll cross-post to github to see what they think.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.