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

Last Updated : 23 Nov, 2021

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:

Getting attributes of Objects in R

Example 1: Implementing attributes() function

R `

R program to illustrate

attributes function

info = data.frame(iris)

Load info set that you want to work on

data(info)

Print first 6 rows of info set data

head(info)

Apply attributes function

attributes(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 class

attributes_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 database

attributes(info) <- attributes_list

attributes(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:

Example: Implementing attr() function

R `

R program to illustrate

attr() function

Load info set that you want to work on

data(info)

Apply attr() function

attr(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.