Skip to content
Prev 67671 / 398506 Next

Multiple copies of attached packages

On Thu, 14 Apr 2005, Liaw, Andy wrote:

            
Not quite.  The correct description is in ?attach (and apart from 
mentioning attach was used, reading the help before posting is de rigeur).
Here is the version from 2.1.0 beta (which has been expanded):

      The database is not actually attached.  Rather, a new environment
      is created on the search path and the elements of a list (including
      columns of a dataframe) or objects in a save file are _copied_
      into the new environment.  If you use '<<-' or 'assign' to assign
      to an attached database, you only alter the attached copy, not the
      original object.  (Normal assignment will place a modified version
      in the user's workspace: see the examples.) For this reason
      'attach' can lead to confusion.

Examples:

      summary(women$height)   # refers to variable 'height' in the data frame
      attach(women)
      summary(height)         # The same variable now available by name
      height <- height*2.54   # Don't do this. It creates a new variable
                              # in the user's workspace
      find("height")
      summary(height)         # The new variable in the workspace
      rm(height)
      summary(height)         # The original variable.
      height <<- height*25.4  # Change the copy in the attached environment
      find("height")
      summary(height)         # The changed copy
      detach("women")
      summary(women$height)   # unchanged

Notice the difference between <- and <<- .

Assigning to an element follows the same rules, and in addition is an 
error unless an object exists that can be suitably subscripted.