What is the attach() function in R?
Overview
The attach() method is used to access variables of a DataFrame without invoking any function or method. This method bypasses extensive built-in and directly attaches variables of a list or DataFrame to the search path.
Syntax
attach(what,pos = 2L,name = deparse(substitute(what),backtick=FALSE),warn.conflicts = TRUE)
Parameters
what: It can either bedatabase,DataFrame,List, NULL or an environment.pos: Its default value is 2L. It shows an integer position in the search index or in the database.name: This is the label used for an attached database.warn.conflicts: The default value isTrue. If set toTrue, it prints the warnings; otherwise, it hides the warnings.
Return value
This method returns either a database, DataFrame, list, or NULL.
Example
The code below shows how the attach() function works:
# Using the R program to illustrate# Creating a sample listRecord <- data.frame(height = c(1, 2, 3, 4, 5),width = c(6, 7, 8, 9, 0),area = c(6, 14, 24, 36, 0))# Indirectly accessing variables of the Record list# Showing the summary of the Recordsummary(Record$height)# Attaching the Record list to the search pathattach(Record)# Showing the summary of the Recordsummary(height)
Explanation
- Lines 3–6: We creating a list that contains three variables:
height,width, andarea.
- Line 9: We use
summary(Record$height)to print the data associated with theheightvariable in theRecordlist. The$sign specifies each variable within a list. To overcome this problem, we use theattach()function. This includes theRecordlist in the search path.
- Line 11: We use
attach(Record)to attach theRecordto the current search path. We can also change the search path explicitly by invokingsearch(). - Line 13: Now,
summary(height)has direct access to theRecordvariables.
Note: We can use the
attach()function in multiple ways according to our needs. The above example is just to give us an overview of the function.