Rmd file which sources an R script which sources another R script

64 Views Asked by At

To make my code modular, I wrote a R script for plotting data, which invokes an R script to prepare the data (to be plotted):

The document.Rmd file contains a line source('./R/customPlot.R') and this script in turns contains a line source('./prepareData.R').

Running the document.Rmd gives me an error message that ./prepareData.R was not found, which could easily be fixed by changing the line in the script customPlot.R to source('./R/prepareData.R).

In this case, however, I could no longer just run customPlot.R on it's own to visually check its output.

My folder structure looks like this:

project/
  Rmd/
    document.Rmd   # calls source('./R/customPlot.R')
  R/
    customPlot.R   # calls source('./prepareData.R')
    prepareData.R

By searching the web, I learned that generating a package of my code might be a possible solution. Although my project is a bit larger, I wanted to ask whether it's worth the overhead. After all, the majority of files in my project are data and actually few of them are code.

1

There are 1 best solutions below

4
Grzegorz Sapijaszko On

Heh, interesting...

The solution might be with here::here() function, like:

project/
  Rmd/
    document.Rmd  
      #'
      source(file = "../R/1.R")
      #'
  R/
    customPlot.R
      #' 
      source(file =  paste0(here::here(), "/R/prepareData.R"))
      #'
    prepareData.R