Getting attributes of Objects in R Language – attributes() and attr() Function
attribute() function in R Programming Language is used to get all the attributes of data. This function is also used to set new attributes to data.
Syntax: attributes(x)
Parameters:
- x: object whose attributes to be accessed.
Getting attributes of Objects in R
Example 1: Implementing attributes() function
R
# R program to illustrate# attributes functioninfo = data.frame(iris)# Load info set that you want to work ondata(info)# Print first 6 rows of info set data head(info) # Apply attributes functionattributes(info) |
Output:
Here in the above code, we have applied the attributes() function so we have shown all the data which is present in the info data frame. So by applying info all the attributes in the datasets will be shown.
Example 2: Assigning new value to the attributes in R language
R
# Set different column names# retain dataframe classattributes_list <- list(names = c('Sepal.Length' ,'Sepal.Width' , 'Petal.Length', 'Petal.Width', 'Species'), class = "data.frame", row.names= c("NA","NA","NA","NA"))# New attributes from list added to info databaseattributes(info) <- attributes_listattributes(info) |
Output:
$names 'Sepal.Length' 'Sepal.Width' 'Petal.Length' 'Petal.Width' 'Species' $class 'data.frame' $row.names 'NA' 'NA' 'NA' 'NA'
Here in the above code, we have added the new attributes to the list info from Example 1, and then printed all the attributes including the new one.
attr() Function
attr() will return specific data, but this function needs precise information about the data.
Syntax:
attr(x = data, which = “attribute_name”)Parameters:
- x: object whose attributes to be accessed.
- which: string specifying the attribute to be accessed.
Example: Implementing attr() function
R
# R program to illustrate# attr() function# Load info set that you want to work ondata(info)# Apply attr() functionattr(x = info, which = "names") |
Output:
'Sepal.Length' 'Sepal.Width' 'Petal.Length' 'Petal.Width' 'Species'
Here in the above code, we have specified a particular parameter name, so only the values in names will be returned. attr() will return specific data, but attr() functions need a precise information about the data.


