0

I am trying to use a file from a different directory, but I need the file to accessible from any directory. Thus, I wanted to start the file path with .. However, doing this throws an error that the file is not available. Is there a way to go to a parent directory in R? This is what I currently have (which throws the error):

source("../src/functions.r")
Ellie
  • 117
  • 2
  • 8
  • 2
    Are you sure you have the correct relative path to your current working directory `getwd()`? The path is not relative to the file in which it's contained; it's relative to the current working directory. A more complete [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) would be helpful here. – MrFlick Jun 19 '18 at 19:10
  • @MrFlick Yes, I have ensured this is the correct relative path – Ellie Jun 19 '18 at 19:13
  • Why don't you use the full path? Depending on your operating system you can just copy a file and paste it into R. The result will look like this `file:///C:/path/src/functions.r`. Get rid of the "file:///" part and put some quotation marks around it and there you go. – JBGruber Jun 19 '18 at 19:16
  • That still doesn't sound right. It sounds like you are trying to source a file (file1.R) from anywhere and file1.R sources a different file called file2.R. Is that right. Then file1.R cannot use a relative path for file2.R because it doesn't have any control over the current working directory. This situation is generally "solved" by creating your own R package. – MrFlick Jun 19 '18 at 19:16

1 Answers1

1

In R, all paths are relative to a working directory. You can use getwd() to obtain the current working directory. To change the directory, use setwd("/path/to/your/working/directory").

If you have a permanent path in which the file functions.r will always be present, then you can use source("/path/to/permanent/directory/functions.r"). It cannot be a relative path starting with .., it needs to be an absolute path from the root directory.

If you are using RStudio, an option would be to create a Project; in this case, the project directory is automatically set as the working directory, and you can access all paths relative to that directory.

Anindya Mozumdar
  • 483
  • 2
  • 11