attach & detach Functions in R | 2 Examples: Data Frame & Package

 

In this article I will show you how to handle data.frames with the attach and detach functions in R. Let’s start with the basic R syntax and the definition of the two functions.

 

Basic R Syntax:

attach(data)
detach(data)

 

Definition:

The attach function allows to access variables of a data.frame without calling the data.frame.

The detach function can be used to:

  • Remove the attachment of a data.frame, which was previously attached with the attach function.
  • Unload a package, which was previously loaded with the library function.

 

In the following tutorial, I will show you two examples for the attach and detach functions in the R programming language. So without further ado, let’s get started!

 

Example 1: Attach & Detach Data Frame in R

Typically, the attach and detach R functions are applied to data frames. So let’s first create an example data frame in R:

data <- data.frame(x1 = c(9, 8, 3, 4, 8),         # Create example data
                   x2 = c(5, 4, 7, 1, 1),
                   x3 = c(1, 2, 3, 4, 5))
data                                              # Print data to RStudio console

 

Example Data Table in R

Table 1: Example Data Frame in R.

 

Our example data consists of three columns and five rows. Let’s assume that we want to work with the first column X1. If we try to call the column with the following code, R returns an error message:

x1                                                # Try to print x1 column without attach
# Error: object 'x1' not found

However, if we attach the data frame first…

attach(data)                                      # Attach data to Global Environment

…we can work with the X1 column:

x1                                                # Print x1 column to RStudio console
# 9 8 3 4 8

After finishing the work on our data frame, it is advisable to detach the data. Otherwise, the R code might get difficult to use afterwards.

We can detach our data with the following line of code:

detach(data)

After detaching, we cannot work with the X1 column as before anymore:

x1                                                # Try to print x1 after detaching
# Error: object 'x1' not found

You can learn more on the code of the previous example in the following video tutorial:

 

 

Note: An alternative to attach and detach is the $-operator. If we just quickly want to use a column (such as X1 of our example data), we can simply use the following line of R code:

data$x1                                           # Call column without attaching data
# 9 8 3 4 8

As you can see, with the $-operator we get the same output as with attach.

In the end, it is a matter of programming style and taste, how often you want to use the attach and detach functions. Some programmers even prefer to never use attach and detach, since it makes an R code more difficult to read.

 

Example 2: Detach Package in R

The detach function can also be applied to R packages. Let’s assume that we have loaded the dplyr package at an earlier point of our code:

install.packages("dplyr")                         # Install dplyr package
library("dplyr")                                  # Load/attach dplyr package

For instance, the dplyr package contains the as.tbl function, which converts a data frame to a tibble object:

data_tbl <- as.tbl(data)                          # Apply as.tbl function of dplyr package

Now let’s assume that we don’t need the package at a later point of our code anymore and for that reason we want to unload the package. Then we can use the detach function as follows:

detach("package:dplyr")

As you can see, the as.tbl function (as well as all other dplyr functions) are not available anymore:

data_tbl <- as.tbl(data)                          # Apply as.tbl after detaching dplyr package
# Error in as.tbl(data) : could not find function "as.tbl"

 

Video Examples: How to Attach Data in RStudio

Do you want to see some more examples for the attach function? Then I can recommend the following video of the DevNami YouTube channel. In the video, the speaker explains how to use the attach function in a live example in RStudio.

Have fun with the video and let me know in the comments, in case you have any further questions or feedback.

 

 

Further Reading

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


4 Comments. Leave new

  • SHRINIVAS DHARMADHIKARI
    April 6, 2019 2:28 am

    very useful.Sometimes with long data frame and variable names, it is really a pain to access a variable repeatedly. attach will help

    Reply
    • Thanks for your comment @Shrinivas! Yes, I definitely agree. Especially when you work for a longer time with the same data.frame, attach can make your life much easier.

      Reply
  • nektarios makris
    October 29, 2019 4:31 pm

    Hi, have a nice day. This article just saved me tons of time.Thank you very much!

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top