2

I have a directory structure as follows

script1.R

dir1/
  script2.R 
  script3.R

  dir2/
    data.csv

script1.R calls and executes script2.R. script2.R executes and reads script3.R and data.csv.

script1.R

source('dir1/script2.R')

script2.R

setwd(dirname(rstudioapi::getSourceEditorContext()$path))
source('script3.R')
source('dir2/data.csv')

If I set my wd() to where script1.R is located and try running script2.R (not through source, but executing it directly), it works fine. If I try executing script2.R from script1.R via source, I get the following error:

Error in file(filename, "r", encoding = encoding) : 
  cannot open the connection
In addition: Warning message:
In file(filename, "r", encoding = encoding) :

 Show Traceback

 Rerun with Debug
 Error in file(filename, "r", encoding = encoding) : 
  cannot open the connection 

I'm pretty stumped on what I'm doing wrong.

Edit-

Within script1.R; I have tried the following, but am getting the same error:

setwd(paste0(getwd(), '/dir1'))
source('script2.R')
CorerMaximus
  • 653
  • 5
  • 15
  • Did you look at https://stackoverflow.com/questions/13672720/r-command-for-setting-working-directory-to-source-file-location-in-rstudio? – Chelmy88 Aug 21 '19 at 18:08

1 Answers1

1

I dug into documention on the source command and changed my code accordingly. This works (added chdir=TRUE from script1.R and removed setwd() from script2.R): script1.R

source('dir1/script2.R'
local=TRUE,
echo=TRUE,
spaced=TRUE,
chdir=TRUE)

script2.R

source('script3.R')
source('dir2/data.csv')

https://www.rdocumentation.org/packages/base/versions/3.6.1/topics/source

CorerMaximus
  • 653
  • 5
  • 15