Skip to content
Prev 383459 / 398502 Next

deciphering help for `attach`

Dear Edward,

Paragraph 4 in the help page goes on to say, "Rather, a new environment is created on the search path and the elements of a list (including columns of a data frame) or objects in a save file or an environment are copied into the new environment."

That seems reasonably clear to me. Here's an example that also illustrates how attach can lead to confusion:

------- snip --------
'data.frame':	50 obs. of  2 variables:
 $ speed: num  4 4 7 7 8 9 10 10 10 11 ...
 $ dist : num  2 10 4 22 16 10 18 26 34 17 ...
[1] ".GlobalEnv"        "cars"              "tools:rstudio"     "package:stats"    
 [5] "package:graphics"  "package:grDevices" "package:utils"     "package:datasets" 
 [9] "package:methods"   "Autoloads"         "package:base"
character(0)
[1] "dist"  "speed"
num [1:50] 2 10 4 22 16 10 18 26 34 17 ...
[1] 1 2 3 4 5 6
[1]  2 10  4 22 16 10
[1] 10  9  8  7  6  5

------- snip --------

Paragraph 5 also seems clear to me. Here's an example:

------- snip --------
[1] ".GlobalEnv"        "NULL"              "cars"              "tools:rstudio"    
 [5] "package:stats"     "package:graphics"  "package:grDevices" "package:utils"    
 [9] "package:datasets"  "package:methods"   "Autoloads"         "package:base"
[1] 10

------- snip --------

Now that may beg the question of why one would want to do something like this, which isn't addressed in the help file, but a fair comment is that if you don't need to store objects in an environment that's accessible on the path, why worry about it? After all, no one is forcing you to use this trick.

Finally, I too recommended that students use attach() when I first starting teaching with R, until I noticed that they frequently tied themselves into knots by attaching different versions of the same data during a session, producing confusion about where the data were coming from and what version they were using. It's not hard in R to avoid the use of attach(). Of course, attach() is still part of the language, so you, and your students, are free to continue using it if you wish, and perhaps your students avoid the problems that mine often created.

Best,
 John

  -----------------------------
  John Fox, Professor Emeritus
  McMaster University
  Hamilton, Ontario, Canada
  Web: http::/socserv.mcmaster.ca/jfox
Message-ID: <385EEAF3-0534-42AF-B7C1-37DF76345255@mcmaster.ca>
In-Reply-To: <20751_1587994317_03RDVrcr024245_3755804f995348996db3b45ba20ca858.squirrel@webmail.psu.ac.th>