[R] .Rprofile replacement function setwd() causing errors

Michael Friendly friendly at yorku.ca
Fri Oct 30 14:30:20 CET 2009


In my .Rprofile  I have the following functions which display the 
current directory in the main R window title bar,
and modify base::setwd() to keep this up to date.  I like this because I 
can always tell where I am in the file system.

cd <- function(dir) {
  base::setwd(dir)
  utils::setWindowTitle( short.path(base::getwd()) )
}

short.path <- function(dir, len=2) {
    np <-length(parts <- unlist(strsplit(dir, '/')))
    parts <-rev( rev(parts)[1:min(np,len)] )
    dots <- ifelse (np>len, '...', '')
    paste(dots,paste(parts, '/', sep='', collapse=''))
}

utils::setWindowTitle(short.path(base::getwd()))
utils::assignInNamespace("setwd",
    function(dir){
        .Internal(setwd(dir))
        utils::setWindowTitle( short.path(base::getwd()) )
        },
    "base")

However, this causes errors in some cases where setwd is used by other 
functions, particularly example():

 > library(HistData)
 > example(Snow)
Error in setwd(olddir) : cannot change working directory
 > traceback()
6: setwd(olddir)
5: open.srcfile(srcfile, first)
4: open(srcfile, first)
3: getSrcLines(srcfile, lastshown + 1, srcref[3L])
2: source(zfile, local, echo = echo, prompt.echo = paste(prompt.prefix,
       getOption("prompt"), sep = ""), continue.echo = paste(prompt.prefix,
       getOption("continue"), sep = ""), verbose = verbose, 
max.deparse.length = Inf,
       encoding = encoding, skip.echo = skips, keep.source = TRUE)
1: example(Snow)
 >

Questions:
*  Is there someway I can re-write these functions to avoid such problems?
* Is there someway I can 'hide' my custom functions like cd(), 
short.path() so they don't appear in the global
environment but are available in my R session?

thanks
-Michael

-- 
Michael Friendly     Email: friendly AT yorku DOT ca 
Professor, Psychology Dept.
York University      Voice: 416 736-5115 x66249 Fax: 416 736-5814
4700 Keele Street    http://www.math.yorku.ca/SCS/friendly.html
Toronto, ONT  M3J 1P3 CANADA



More information about the R-help mailing list