[R] where does R search when source()?

Marc Schwartz MSchwartz at MedAnalytics.com
Sun Jul 11 03:48:30 CEST 2004

On Sat, 2004-07-10 at 20:13, Spencer Graves wrote:
>   In case no one who knows has time to reply to this, I will report on 
> my empirical investigation of this question using R 1.9.1 under Windows 
> 2000. First, I saved a simple script file "tst-source.R" in the working 
> directory, e.g., "d:/sg/proj1". When I said, "source('tst-source.R')", 
> it sourced the file appropriately. Then I moved this file to the 
> immediate parent, e.g., "d:/sg" and tried the same source command. It 
> replied, "Error ... unable to open connection ... ." Then I got a 
> command prompt, said, "path", and moved the file into one of the 
> directories in the search path. When I repeated the "source" command, it 
> was still "unable to open connection ... ."
> Conclusion: From this and other experiences, I have found three ways to 
> specify file names:
> (1) If the complete path and file name are supplied for an existing 
> file, 'source' will find it.
> (2) If a file is in the working directory, specifying that name will get 
> it.
> (3) If a file is in a subdirectory of the working directory, e.g., 
> "d:/sg/proj1/sub1/tst-source.R", then specifying 
> "source('sub1/tst-source.R')" will get it.
> hope this helps. spencer graves
> Shin, Daehyok wrote:
> >Exactly where does R search for foo.R if I type source(`foo.R')?
> >Only from current working directory (same as getwd()), from all directories
> >specified by e.g. $PATH?  Thanks.
> >
> >Daehyok Shin

The relevant code snippet from source() is:

    Ne <- length(exprs <- parse(n = -1, file = file))

Note that the argument 'file' from the initial call to source() is used
'as is' in the 'file = file' argument to parse(). There is no searching
of the $PATH.

Thus, the file will be used based upon either the filename itself or a
proper absolute or relative path as Spencer notes above. If the filename
only is used, it needs to be in the current working directory or you get
the error that Spencer experienced.


Marc Schwartz

More information about the R-help mailing list