Skip to content

locked binding of setwd() in R 2.15.x causes .Rprofile to fail

2 messages · Michael Friendly, William Dunlap

#
[Env: Win XP, R 2.14.2, R 2.15.0]

I have a replacement function for setwd() in my .Rprofile which displays 
the current R path in the R window
title. It no longer works in R 2.15.x, giving the error below. Worse, 
the error prevents the rest of my
.Rprofile script from completing.

Is there some way to rescue this, i.e., preserve this behavior in
R 2.15? If not, how can I modify my script so it will still work under R 
2.14.2 and not fail under R 2.15?

Error in utils::assignInNamespace("setwd", function(dir) { :
locked binding of ?setwd? cannot be changed

######################
#-- functions from .Rprofile
# modify setwd() to also show the current path in the window title
# assigns .lastdir in the global environment
local({
oldsetwd <- setwd
utils::assignInNamespace("setwd",
function(dir) {
.lastdir <<- oldsetwd(dir)
utils::setWindowTitle( short.path(base::getwd()) )
.lastdir
}, "base")
})

# setwd replacement, allowing cd() to be like 'cd -' on unix (return to 
last dir)
cd <- function(dir) {
if(missing(dir)) dir <- .lastdir
.lastdir <<- 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=''))
}
#
Does trace() do what you want from a .Rprofile file?  It works
from the command line:

  > trace(setwd,print=FALSE,quote(options(prompt=paste0(dir,"> "))))
  Tracing function "setwd" in
  package "base"
  [1] "setwd"
  > setwd("z:/")
  z:/> getwd()
  [1] "z:/"
  z:/> setwd("c:/temp")
  c:/temp> pi
  [1] 3.141593
  c:/temp>

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com