Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.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"))
like image 762
Dolan Antenucci Avatar asked Aug 28 '11 16:08

Dolan Antenucci


1 Answers

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.

like image 186
Apprentice Queue Avatar answered Oct 23 '22 21:10

Apprentice Queue