2

I'm developing an R package, one of my package function is generate_report() which generate an html report with rmarkdown using a templete Rmd file and function arguments:

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

and here is the inst/templete.Rmd file: (when the package is compiled, it will be moved to top-level folder of package:

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

## Head 1

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

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

my question is, when the package is devtools::install()ed, function generate_report() can not find file templete.Rmd, how to make the function find this templete.Rmd file in right way ?

Jia Ru
  • 93
  • 6
  • You should use `system.file()` to get the path to the file in your package (otherwise R by default uses the current working directory). See: http://r-pkgs.had.co.nz/inst.html – MrFlick Jul 07 '17 at 04:59
  • Possible duplicate: https://stackoverflow.com/questions/25938814/package-compilation-and-relative-path/25997946 – MrFlick Jul 07 '17 at 05:02

2 Answers2

0

Your rmarkdown::render() call needs to use system.file as per http://r-pkgs.had.co.nz/inst.html

Jonathan Carroll
  • 3,897
  • 14
  • 34
0

system.file is the right way, thanks @MrFlick and @Jonathan Carroll. This is my final code:

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)
    }
Jia Ru
  • 93
  • 6