Determining current file's location in R to include file from same directory?
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开发者_Python百科.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.
精彩评论