Skip to content
Prev 383556 / 398502 Next

deciphering help for `attach`

Hallo

Sorry for confusion. John explained in technical language what I was trying to explain in plain one. One cannot simply change values in original data frame or call them, however they could be used in functions.

Consider this

attach(cars)
speed <- speed*2
speed
 [1]  8  8 14 14 16 18 20 20 20 22 22 24 24 24 24 26 26 26 26 28 28 28 28 30 30
[26] 30 32 32 34 34 34 36 36 36 36 38 38 38 40 40 40 40 40 44 46 48 48 48 48 50
plot(speed, dist)
fit <- lm(dist~speed, data=cars)
abline(fit)
fit1 <- lm(dist~speed)
abline(fit1, col = 2)

And if you attach something which has speed and dist variable inside, the things could be even more confusing.

mydata <- data.frame(speed="Blue", dist="Black")
attach(mydata)
The following object is masked _by_ .GlobalEnv:

    speed

The following objects are masked from cars:

    dist, speed
[1] ".GlobalEnv"        "mydata"            "cars"             
 [4] "package:stats"     "package:datasets"  "package:fun"      
 [7] "package:utils"     "package:grDevices" "package:graphics" 
[10] "package:methods"   "Autoloads"         "package:base"     

So although mydata are attached its speed variable is accessible only by referencing to mydata, but now dist from mydata is used in lm, if cars data frame is not specified.
Error in model.frame.default(formula = dist ~ speed, drop.unused.levels = TRUE) : 
  variable lengths differ (found for 'speed')
[1]  8  8 14 14 16 18 20 20 20 22 22 24 24 24 24 26 26 26 26 28 28 28 28 30 30
[26] 30 32 32 34 34 34 36 36 36 36 38 38 38 40 40 40 40 40 44 46 48 48 48 48 50
[1] "Black"

I used attach myself a lot about 20 years ago but due to unexpected (by myself) behaviour I do not use it now. Of course nobody will prevent you to use or teach attach, but you has to acknowledge that attach is doing what it is doing and not what you or your students expect it is doing. And for me, environments are still something I did not familiarise with.

Cheers
Petr