[R] setting the current working directory to the location of the source file

Charles C. Berry cberry at tajo.ucsd.edu
Fri Jun 11 07:40:42 CEST 2010


On Fri, 11 Jun 2010, Marcin Gomulka wrote:

> AFAIK a script run through source() does not have any legit way to learn
> about it's own location.
>

You mean like 'test.R' being able to figure out that that is what it is 
called when it is invoked from source()?


> cat("print(eval(sys.calls()[[1]][[2]]))",file='test.R')
> source('test.R')
[1] "test.R"
> setwd('projects')
> source('../test.R')
[1] "../test.R"
> source(list.files('..','test.R$',full=TRUE))
[1] "../test.R"
>
>

See

 	?sys.calls


HTH,

Chuck


> I need this to make sure that the script will find its datafiles after I
> move the whole directory. (The datafiles are in the same directory.)
>
> Here is a hack I invented to work around it:
>
> print(getwd())
> source_pathname  = get("ofile",envir = parent.frame())
> source_dirname = dirname(source_pathname )
> setwd(source_dirname)
> print(getwd())
>
> Question: Is there a better, cleaner way?
>
> Thanks,
> mrgomel
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

Charles C. Berry                            (858) 534-2098
                                             Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	            UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/  La Jolla, San Diego 92093-0901



More information about the R-help mailing list