How can I point an R file from the parent directory through the shell?

I can run the R script from the IDE (Rstudio), but not from a command line call. Is there a way to do this without supplying the full path?

The file I want to use is in the parent directory.

It works:

source('../myfile.R')  #in a call from Rstudio

      

However, it is not:

>  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

      

It seems like it should be simple, but ...

Edit: I'm using GNU bash, version 3.2.53 (1) -release (x86_64-apple-darwin13)

+3


source to share


1 answer


In R, relative file locations are always relative to the current working directory. You can explicitly specify your working directory like this:

setwd("~/some/location")

      

Once this is installed, you can get the 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, for example, in the parent directory, but links to files relative to its location? Use the parameter chdir=

in source

:

source("../another_script.R", chdir = TRUE)

      

This temporarily changes the working directory to the directory containing the original file while checking the source. After that, your working directory will be set to what it was before it was started source

.

+8


source







All Articles