Accessing variables of a data frame in R Programming – attach() and detach() function

attach() function in R Language is used to access the variables present in the data framework without calling the data frame.

Syntax: attach(data, pos)

Parameters:
data: data frame
pos: position of database

Example: attach() function

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to illustrate
# attach function
  
# Create example data
data <- data.frame(x1 = c(1, 2, 3, 4, 5),         
                   x2 = c(6, 7, 8, 9, 0),
                   x3 = c(1, 2, 5, 4, 5))
  
# Try to print x1
# Error: object 'x1' not found
  
# attach data
attach(data, pos = x1)                                            

chevron_right


Output:



1 2 3 4 5

Here in the above code, we have created a data framework and assigned a value to it, when we tried to return value an error occurred.
Then we use the attach function and returned value of x1.

detach() Function

detach() function is used to remove the attachment in data framework that was made by attach() function.

Syntax: detach(data, unload)

Parameters:
data: data frame
unload: boolean value

Example: detach() Function

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to illustrate
# detach function
  
# Install dplyr package
install.packages("dplyr")
  
# attach dplyr
library("dplyr")                                
  
# Apply as.tbl function of dplyr package
data_tbl <- as.tbl(data)                         
  
detach("package:dplyr", unload = FALSE)
  
# Apply as.tbl after detaching dplyr package
data_tbl <- as.tbl(data)

chevron_right


Output:

Error in as.tbl(data) : could not find function "as.tbl"

Here in the above code, we have installed a dplyr package and used its function as.tbl. Then we detach the package and try to use the function again, and an error occurred.
detach functions are used to unpack the libraries which were added to the library.




My Personal Notes arrow_drop_up

Check this out nerdboinet

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.