Attach & Detach Data Frame in R (Example)
This page shows how to attach and detach data frames in the R programming language.
Example Data
my_data <- data.frame(x = c(7, 1, 1, 5), # Create example data y = c(3, 2, 3, 1), z = c(8, 5, 8, 2)) my_data # Show data in console # x y z # 7 3 8 # 1 2 5 # 1 3 8 # 5 1 2 |
my_data <- data.frame(x = c(7, 1, 1, 5), # Create example data y = c(3, 2, 3, 1), z = c(8, 5, 8, 2)) my_data # Show data in console # x y z # 7 3 8 # 1 2 5 # 1 3 8 # 5 1 2
Example for the Application of attach() & detach()
If we try to use the first column of our example data without the prefix my_data$, the RStudio console returns an error:
x # Try to access the column x # Error: object 'x' not found |
x # Try to access the column x # Error: object 'x' not found
However, we can attach our data frame as follows:
attach(my_data) # Attach data frame |
attach(my_data) # Attach data frame
Now, we can access the column x by simply typing it’s name:
x # Try to access the column x # 7 1 1 5 |
x # Try to access the column x # 7 1 1 5
Once we are finished working on our data, we can detach the data frame:
detach(my_data) # Detach data frame |
detach(my_data) # Detach data frame
The column x can not be accessed without the prefix my_data$ anymore:
x # Try to access the column x # Error: object 'x' not found |
x # Try to access the column x # Error: object 'x' not found
The attach and detach functions are very useful when you want to work for a longer time on the same data object. However, you should be careful, because for inexperienced R users the code might get harder to read.