I'm able to source an R script from the IDE (Rstudio), but not from a command line call. Is there a way to do this without having to supply the full path?
The file I want to source is in the parent directory.
This works:
source('../myfile.R') #in a call from Rstudio
However, this doesn't:
> Rscript filethatsources_myfile.R
Error in file(filename, "r", encoding = encoding) :
cannot open the connection
Calls: source -> file
In addition: Warning message:
In file(filename, "r", encoding = encoding) :
cannot open file '../myfile.R': No such file or directory
Execution halted
This seems like it should be simple, but...
Edit: I'm using GNU bash, version 3.2.53(1)-release (x86_64-apple-darwin13)
In R, relative file locations are always relative to the current working directory. You can explicitly set your working directory like so:
setwd("~/some/location")
Once this is set, you can get your source file relative to the current working directory.
source("some_script.R") # In this directory
source("../another_script.R") # In the parent directory
source("folder/stuff.R") # In a child directory
Not sure what your current working directory is? You can check by submitting getwd()
.
What if your source file is in, for example, the parent directory but references files relative to its location? Use the chdir=
option in source
:
source("../another_script.R", chdir = TRUE)
This temporarily changes the working directory to the directory containing the source file for the duration of the source evaluation. Once that's done, your working directory is set back to what it was prior to running source
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With