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

attributes() Function

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.

attr() Function

The attr() function is used to access or modify a specific attribute of an object. Unlike attributes(), it requires you to specify the name of the attribute you want to retrieve or update.

Syntax:

attr(x, which = "attribute_name")

Parameters:

  • x: The object whose attribute is to be accessed or modified.
  • which: The name of the attribute to be accessed or modified.

Example: Accessing a Specific Attribute

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

# Retrieve the column names using attr()
attr(x = data_set, which = "names")

Output:

[1] "Name"  "Age"   "Score"

Here, the attr() function retrieves the column names of the data_set data frame.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *