[R] detach()

Rolf Turner rolf at math.unb.ca
Mon Mar 22 17:56:01 CET 2004


I got bitten recently by the following behaviour of detach();

 > save(file="Junk")
 > attach("Junk")
 > search()
 [1] ".GlobalEnv"      "file:Junk"       "package:methods" "package:ctest"  
 [5] "package:mva"     "package:modreg"  "package:nls"     "package:ts"     
 [9] "package:Misc"    "Autoloads"       "package:base"   
 > detach(2)
 > # No problem; reattach junk.
 > attach("Junk")
 > ind <- 2
 > detach(ind)
Error in detach(ind) : invalid name
 > is.numeric(ind)
[1] TRUE

The help on detach() says:

    name: The object to detach.  Defaults to 'search()[pos]'. This can
          be a name or a character string but _not_ a character vector. 

     pos: Index position in 'search()' of database to detach.  When
          'name' is 'numeric', 'pos = name' is used.           ^^^^ 
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Looking at the code of detach, I see that name gets assigned
substitute(name) before the check as to whether name is numeric.  So
if name is provided as an object --- like ind --- then name becomes
the name ``ind'' and is an object of mode "name" and so the check
will evaluate to FALSE.  (If name is given as an explicit constant
--- like 2 --- then name remains equal to 2 and is indeed numeric so
the check evaluates TRUE.)

Is this the intended behaviour for detach() or is it a bug?

It's obviously no big deal because detach(pos=ind) works perfectly.
But it did trip me up and could conceivably trip others.

				cheers,

					Rolf Turner
					rolf at math.unb.ca




More information about the R-help mailing list