使用 templete 开发 R 包 .Rmd 文件可找到包功能

developing R package with templete .Rmd files findable to package function

我正在开发一个 R 包,我的包函数之一是 generate_report(),它使用模板 Rmd 文件和函数参数生成带有 rmarkdown 的 html 报告:

#' generate report based on templete file
#' @import rmarkdown
#' @export
generate_report <- function(x, y){
  rmarkdown::render('templete.Rmd', envir = list(x = x, y = y))
}

这里是inst/templete.Rmd文件:(编译包时,它会被移动到包的顶层文件夹:

---
title: "templete"
output: html_document
---

## Head 1

```{r}
print(x)
```

```{r}
print(y)
```

我的问题是,当包被 devtools::install()ed 时,函数 generate_report() 找不到文件 templete.Rmd,如何让函数找到这个 templete.Rmd 文件正确的方法?

您的 rmarkdown::render() 调用需要根据 http://r-pkgs.had.co.nz/inst.html

使用 system.file

system.file 是正确的方法,感谢@MrFlick 和@Jonathan Carroll。这是我的最终代码:

generate_report <- function(x, y, output_dir){
      file <- system.file("templete.Rmd", package = 'mypackage-name')
      if (missing(output_dir)) {
         output_dir <- getwd()
      }
      rmarkdown::render(file, envir = list(x = x, y = y), output_dir = output_dir)
    }