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 be database, 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 is True. If set to True, 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 list
Record <- 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 Record
summary(Record$height)
# Attaching the Record list to the search path
attach(Record)
# Showing the summary of the Record
summary(height)

Explanation

  • Lines 3–6: We creating a list that contains three variables: height, width, and area.
  • Line 9: We use summary(Record$height) to print the data associated with the height variable in theRecord list. The $ sign specifies each variable within a list. To overcome this problem, we use the attach() function. This includes the Record list in the search path.
  • Line 11: We use attach(Record) to attach the Record to the current search path. We can also change the search path explicitly by invoking search().
  • Line 13: Now, summary(height) has direct access to the Record variables.

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.

New on Educative
Learn any Language for FREE all September 🎉
For the entire month of September, get unlimited access to our entire catalog of beginner coding resources.
🎁 G i v e a w a y
30 Days of Code
Complete Educative’s daily coding challenge every day in September, and win exciting Prizes.

Free Resources