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.
Examples:
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
detach(file)
gives:
Error in detach(file) : invalid name
That's surprise number 1.
Oh well, lets type the filename out:
detach("foo.RData")
gives:
Error in detach("foo.RData") :
invalid name
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:
detach("file:foo.RData")
and that works nicely. No surprise there, except perhaps that nothing
surprising happened.
So, maybe you can attach() with a 'file:' prefix?
attach("file:foo.RData")
gives:
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)
print(search()[pos])
eval(substitute(detach(n), list(n=name)))
}
- and that doesn't work for attached data files because of the
'file:'
prefix.
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...
Barry