Reputation: 15942
I want to be able to source()
a file which includes a different file in its same directory, but I don't want to have to set the working directory from the R-prompt before running this file:
> getwd()
[1] "/Users/myser"
> source("/Users/myuser/workspace/myproject/myfile.r")
Inside /Users/myuser/workspace/myproject, there would be myfile.r and my-utils.r. myfile.r calls source('my-utils.r')
from within it.
Other programming languages can determine the current file's path. Does R have something similar? Example:
cur_dir <- sys.get_current_file_path()
source(file.path(cur_dir, "my-utils.r"))
Upvotes: 10
Views: 4412
Reputation: 798
I know it's very late, but for people of the future, I ran into this answer on getting the directory where the script being sourced is.
I think you should be able to do this without installing additional packages:
cur_dir = utils::getSrcDirectory(function(){})[1]
source(file.path(cur_dir, 'my-utils.R'))
Upvotes: 0
Reputation: 2036
source("/Users/myuser/workspace/myproject/my-utils.r", chdir=TRUE)
When chdir
option is set to true and the source file parameter is a full path, the directory of file will be used as the working directory while sourcing the file.
NOTE: cur_dir <- sys.get_current_file_path()
doesn't make much sense because pathnames are not unique.
Upvotes: 11