Set an .Rmd in a package to write files to the current project working directory

Viewed 1152

I have a .Rmd which I use to report on data quality in a number of different r projects. It would then split the data to remove subsets with missing data, and interpolate missing results where appropriate. It would do this via a write.csv command to a file path in the form of "./Cleansed_data/"

To make an example

  1. open rstudio
  2. go to the rhs 'project' menu , and select and make a new project wherever you'd like
  3. go to the lhs 'new script' drop down and select 'new .Rmd'
  4. change the output to .pdf and hit ok
  5. in the last r chunk include write.csv(mtcars, file = "mtcars.csv")
  6. hit the 'knit pdf' button, save the report as "writeFile.Rmd" to your project working directory, and let it run.

Previously I moved this .Rmd from place to place, however now I would like to built it into an internal package. I have included it (as the documentation indicates to) into inst/rmd within the package directory.

  1. In order to do this build or open any package you have access to
  2. add the file to inst/rmd (create it if this doesn't exist)
  3. rebuild the package

I then rebuild the package and open a new project. I load my new package and attempt to run the document via the render command using the system.file command to locate the .rmd like so

rmarkdown::render(input = system.file("rmd/writeFile.Rmd", package="MyPackage"), 
              output_file = "writeFile.pdf", output_dir = "./Cars/)

This will render the report from the package build into the folder from output_dir, however, there are a number of pitfalls here. First, if I omit the output_dir argument, the report will render into the package library, usually located in the libraries r installation in the c drive. This is however fixable.

What I can't get around is that when the .Rmd hits the write.csv() then (I believe) the .Rmd is being rendered in the package environment at the time, the working directory of which is the package library folder, not the current project directory.

The Questions

  1. How can I inform the template in the package what the current working directory is for the rstudio project? I'm vaguely aware there might be a rstudio api package? I have nearly no understanding of what it is though, or if this would provide a solution.
  2. If this is either outright impossible or just potentially a very bad idea how can I modify the workflow to successfully retrieve a number of r object outputs into the environment or the working directory, on the call to the report, without having to modify the report for each different project? Further, why specifically is this approach such a bad plan?
1 Answers
Related