developing shiny app as a package and deploying it to shiny server

我们两清 提交于 2019-11-28 02:51:48

When I make shiny applications as a stand-alone package, I usually organize the files as so:

In the R directory:

  • All of my methods to support the application (these should be exported if they will be used in either the ui.R, server.R, or global.R files)
  • A launch_application function

The definition of launch_application is similar to:

launch_application <- function(x, ...)
{
  shiny::runApp(appDir = system.file("application", package = [my_pkg]),
                ...)
}

In the inst directory

  • application/server.R
  • application/ui.R
  • application/global.R

After building and installing the package, I then just need to run

library(my_pkg)
launch_application(...)

There is already an accepted answer with many votes, but I'd like to add a few things, so I'll answer myself as well. For more information, you can read my article Supplementing your R package with a Shiny app.

This is the folder structure I use:

- mypacakge
  |- inst
      |- myapp
         |- ui.R
         |- server.R
  |- R
     |- runApp.R
     |- ...
  |- DESCRIPTION
  |- ...

Inside the R/ folder is where I place all the non-shiny code. The code for the shiny app itself lives in inst/. The R/runApp.R file is defined as

#' @export
runExample <- function() {
  appDir <- system.file("myapp", package = "mypackage")
  if (appDir == "") {
    stop("Could not find myapp. Try re-installing `mypackage`.", call. = FALSE)
  }

  shiny::runApp(appDir, display.mode = "normal")
}

(You can see this in action; for example, shinyalert uses this structure for its demo app).

In a comment, you asked how can this be deployed on a shiny server. It's simple, you can simply have a file /srv/shiny-server/myapp.app.R that calls and runs that package (after you've installed the package on the server):

dir <- system.file("myapp", package = "mypackage")
setwd(dir)
shiny::shinyAppDir(".")

(You can see this in action as well, code here)

A lot of packages with proof-of-concept Shiny demos are not designed for deployment on Shiny Server, but instead, include something like this in a function meant to be run from RStudio:

fooRun <- function() {
   app <- shinyApp(appUI, appServer)
   runApp(app, launch.browser = TRUE, ...)
}

This function won't work in Shiny Server (you can't run runApp within runApp) but it gives some clues as to how to create an app.R that can act as a placeholder to use in /srv/shiny-server/foo/app.R

library("foo")
shinyApp(ui = foo:::appUI, server = foo:::appServer)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!