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"))
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.
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