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

Duncan Murdoch murdoch at stats.uwo.ca
Fri Oct 30 16:51:02 CET 2009


On 10/30/2009 9:30 AM, Michael Friendly wrote:
> 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")

I would guess this would be fixed if you save the value from the 
.Internal call, and return it as the result of your function, the way 
the standard setwd does.  A safer approach would be something like this:

local({
   oldsetwd <- setwd
   utils::assignInNamespace("setwd",
      function(dir) {
         value <- oldsetwd(dir)
         utils::setWindowTitle( short.path(base::getwd()) )
         value
      }, "base")
})

This way, if the internals of setwd() ever change, your function won't 
break.

Duncan Murdoch


> 
> 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
>




More information about the R-help mailing list