EZ

Eduzan

Learning Hub

Eduzan
Eduzan / R (programming language)

Getting attributes of Objects in R Language – attributes() and attr() Function

Computer Science / R (programming language) tutorial chapter - Published 2025-12-13 - R (programming language)

The attributes() function in R is used to retrieve all the attributes of an object. Additionally, it can be used to set or modify attributes for an object.

Syntax:

attributes(x)

Parameters:

  • x: The object whose attributes are to be accessed or modified.

Example 1: Retrieving Attributes of a Data Frame

# R program to illustrate attributes() function
# Create a data frame
data_set <- data.frame(
  Name = c("Alice", "Bob", "Charlie"),
  Age = c(25, 30, 22),
  Score = c(85, 90, 95)
)

# Print the first few rows of the data frame
head(data_set)

# Retrieve the attributes of the data frame
attributes(data_set)

Output:

$names
[1] "Name"  "Age"   "Score"

$class
[1] "data.frame"

$row.names
[1] 1 2 3

Here, the attributes() function lists all the attributes of the data_set data frame, such as column names, class, and row names.

Example 2: Adding New Attributes to a Data Frame

# R program to add new attributes
# Create a data frame
data_set <- data.frame(
  Name = c("Alice", "Bob", "Charlie"),
  Age = c(25, 30, 22),
  Score = c(85, 90, 95)
)

# Create a list of new attributes
new_attributes <- list(
  names = c("Name", "Age", "Score"),
  class = "data.frame",
  description = "Sample dataset"
)

# Assign new attributes to the data frame
attributes(data_set) <- new_attributes

# Display the updated attributes
attributes(data_set)

Output:

$names
[1] "Name"  "Age"   "Score"

$class
[1] "data.frame"

$description
[1] "Sample dataset"

In this example, a new attribute (description) is added to the data_set data frame, along with retaining existing attributes like column names and class.

End of lesson.