[Rd] attach/detach asymmetry
b.rowlingson at lancaster.ac.uk
Wed May 16 20:54:38 CEST 2007
Is there a good reason why arguments to 'attach' and 'detach' differ so
much? Yes, I know this is the documented behaviour, it just seems to
violate the principle of least surprise.
file = "foo.RData"
df = data.frame(x=1:10,y=1:10)
attach(file) # attaches the RData file 'foo.RData'
attach(df) # attaches the object df
Not surprising in an OO system that a function operating on different
things does different things. However:
detach(df) - works as expected
Error in detach(file) : invalid name
That's surprise number 1.
Oh well, lets type the filename out:
Error in detach("foo.RData") :
Surprise number 2.
Check the search() list, and you see that R has stuck 'file:' on the
start of your file path. So try that:
and that works nicely. No surprise there, except perhaps that nothing
So, maybe you can attach() with a 'file:' prefix?
Error in attach("file:foo.RData") :
file 'file:foo.RData' not found
- in this case it took it literally as a file name. Surprise number 3.
This is all documented behaviour (actually, I cant find any
documentation on the 'file:' prefixing), but am I the only person who
finds it inelegant? Or even downright ugly that the help page for
detach() gives this example code for attaching and detaching by name?
attach_and_detach <- function(db, pos=2)
name <- deparse(substitute(db))
attach(db, pos=pos, name=name)
- and that doesn't work for attached data files because of the 'file:'
I think this could be solved by changing detach(foo) to do something
different if foo is a character string, and adding the 'file:' prefix
internally. Or maybe they need rewriting as proper methods?
Perhaps I'm just being over-sensitive about a matter of aesthetics...
More information about the R-devel