[R] How to source files from a search path?

blue sky bluesky315 at gmail.com
Sat Feb 13 06:52:28 CET 2010


On Fri, Feb 12, 2010 at 11:41 PM, blue sky <bluesky315 at gmail.com> wrote:
> On Fri, Feb 12, 2010 at 6:11 PM, Don MacQueen <macq at llnl.gov> wrote:
>> Well, you still will need Sys.getenv() to get the value of the environment
>> variable into R.
>>
>> Are you familiar with the function named list.files() ?
>>
>> This may do the job:
>>
>>   source( list.files( Sys.getenv('SOMEENVVAR'), pattern='myfilename') )
>>
>> But I haven't tested it.
>
> This doesn't do what I want. Anyway, I made my own program. Let me
> know if a function that does the same thing is available in some other
> packages.
>
> smart.source=function(partial_path) {
>  source(full.path(partial_path))
> }
> full.path=function(partial_path) {
>  found_rpath=base:::Find(
>    function(p) {
>      full_path=base:::file.path(p, partial_path)
>      base:::file.exists(full_path)
>    }
>    , base:::unlist(base:::strsplit(base:::Sys.getenv('RPATH'), ':'))
>    )
>
>  if(is.null(found_rpath)) {
>    stop(paste(partial_path, ' is not found in $RPATH', sep=''))
>  } else {
>    base:::file.path(found_rpath, partial_path)
>  }
> }
>
>
> #shell environment variable
> RPATH=/dir1:/dir2
>
>
> I have the following R file, which is in /dir2.

I mean in /dir2/smart.source/

> $ cat main_test.R
> f=function() {
>  print('in f')
> }
>
>
> Then I can source the above file like the following.
>
>> smart.source('smart.source/main_test.R')
>> f()
> [1] "in f"
>



More information about the R-help mailing list