You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将Shiny应用封装为R包:如何为runExample函数编写文档?

嘿,作为Shiny新手,把应用封装成R包还得写文档确实有点绕!我来给你一步步讲清楚怎么给你的runExample()函数加上规范的R包文档——用现在R包开发标配的roxygen2就行。

给Shiny包的runExample函数添加文档

首先,你已经加了#' @export标签,这很好,接下来只需要补充roxygen2的其他必要标签,就能生成清晰的函数文档了。

1. 完整的带文档的函数示例

直接把这段代码替换你现有的函数(包括上方的注释):

#' Launch the MyPackage Shiny Example App
#'
#' This function starts the Shiny application included in the mypackage R package.
#' If the app directory can't be located (most often due to a failed package installation),
#' it will throw a clear error message guiding you to re-install the package.
#'
#' @details
#' The Shiny app files are stored in the `inst/shiny-examples/myapp` directory of your package source.
#' Make sure this directory structure exists before building or installing your package—otherwise `system.file()` won't find the app.
#'
#' @return Invisible NULL (this function is called for its side effect: launching the interactive Shiny app)
#' @export
#'
#' @examples
#' \dontrun{
#' # Run the example Shiny app
#' runExample()
#' }
runExample <- function() {
  appDir <- system.file("shiny-examples", "myapp", package = "mypackage")
  if (appDir == "") {
    stop("Could not find example directory. Try re-installing `mypackage`.", call. = FALSE)
  }
  shiny::runApp(appDir, display.mode = "normal")
}

2. 关键标签的作用

我给你拆解下每个标签的意义,方便你理解和调整:

  • 第一行#' Launch the MyPackage Shiny Example App:这是函数的标题,要直白告诉用户这个函数能做什么。
  • 第一段描述:解释函数的核心功能,以及错误场景的处理逻辑。
  • @details:补充额外的技术细节,比如App的存放位置,帮助用户排查可能的路径问题。
  • @return:说明函数的返回值——因为shiny::runApp()是启动交互应用,没有实际的返回值,所以标注为Invisible NULL。
  • @examples:用\dontrun{}包裹示例代码,这是因为运行这个示例会直接弹出Shiny App,不适合在R包的自动检查(R CMD check)中执行。
  • @export:你已经添加了这个标签,它确保用户安装包后能直接调用这个函数。

3. 生成并验证文档

写完上面的代码后,你需要做这两步:

  1. 安装并加载devtools包(如果还没装的话:install.packages("devtools")),然后在你的包项目中运行devtools::document()——这会自动生成.Rd格式的文档文件到包的man/目录下。
  2. 重新安装你的包:devtools::install(),之后在R控制台输入?runExample,就能看到你刚写的完整文档了!

额外小提示

  • 确认你的包目录结构正确:Shiny App的所有文件(ui.R、server.R或者app.R)必须放在inst/shiny-examples/myapp/下面——inst/目录下的内容会被完整复制到包的安装目录,这样system.file()才能准确找到App的位置。
  • 如果你的包还没初始化,推荐用devtools::create("mypackage")来生成标准的R包结构,再把App放到对应的inst子目录里。

内容的提问来源于stack exchange,提问作者Bella

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:57:32