# 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) |

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 |

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

**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 |

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 |

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 |

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) |

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 |

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

**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 |

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 |

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 |

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") |

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" |

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 my free statistics newsletter:

### R Tutorials

abs Function in R

all & any R Functions

Set Aspect Ratio of Plot

attach & detach R Functions

attr, attributes & structure in R

cbind R Command

Change ggplot2 Legend Title

Character to Numeric in R

Check if Object is Defined

col & row sums, means & medians

Complete Cases in R

Concatenate Vector of Strings

Convert Date to Weekday

cumsum R Function

Data Frame Column to Numeric

diff Command in R

difftime R Function

dim Function in R

dir R Function

Disable Scientific Notation

Draw Segments in R

droplevels R Example

Evaluate an Expression

Extract Characters from String

Factor to Numeric in R

Format Decimal Places

get, get0 & mget in R

is.na R Function

is.null Function in R

jitter R Function

Join Data with dplyr Package

length Function in R

lowess R Smoothing Function

max and min Functions in R

NA Omit in R

nchar R Function

ncol Function in R

nrow Function in R

outer Function in R

pairs & ggpairs Plot

parse, deparse & R expression

paste & paste0 Functions in R

pmax and pmin R Functions

polygon Plots in R

pretty R Function

R Find Missing Values

R Functions List (+ Examples)

R NA – Values

R Replace NA with 0

rbind & rbind.fill in R

Read Excel Files in R

readLines, n.readLines & readline

Remove Element from List

Remove Legend in ggplot2

Rename Column Name in R

Replace Last Comma of String

rev R Command

Round Numeric Data in R

Save & Load RData Workspace

scan R Function

setdiff R Function

setNames vs. setnames in R

sink Command in R

Sort, Order & Rank Data in R

sprintf Function in R

Square Root in R

str_c Function of stringr Package

str_sub Function of stringr Package

strptime & strftime Functions

substr & substring R Commands

sweep R Function

Transform Data Frames

union Function in R

unlist in R

weekdays, months, quarters & julian in R

with & within R Functions

Write Excel File in R

## 2 Comments. Leave new

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

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.