logo

Referencing Metadata and attr in R 📂R

Referencing Metadata and attr in R

Overview

When using various functions in R, you might occasionally come across data like attr(,"something"). The term Attribute literally means property. Unlike languages like Python, in R, attributes can be thought of as metadata or a form of annotation within the data. Sometimes, while using R, you might find the need to refer to this data.

Example

20190605\_203648.png
For instance, after performing standardization, the mean is stored as attr(,"scaled:center") and the standard deviation as attr(,"scaled:scale"). Although it’s not strictly necessary to reference these attributes to obtain the mean and standard deviation, you should be able to do so if you wish.

20190605\_203706.png
To access the metadata, you can use the attributes() function. attributes() returns all the metadata, including the dimensions of the data. Once returned, you can simply reference it using the $ operator.

20190605\_204020.png
However, if you only need to view a specific piece of metadata rather than checking all of it, you can use the attr() function as shown above to directly return the desired metadata.

On the other hand, attr() can also be used to add metadata. For example, given an arithmetic sequence, you can use the attr() function to embed properties such as the sequence’s nature, its first term, and common difference directly into the data.

20190605\_204039.png
Since it is just metadata, you can see that using conventional functions like sum() will work correctly as though the metadata were not present. If you are involved in complex programming, it may be worth considering its active usage.

Code

set.seed(150421)
x<-rnorm(10)
z<-scale(x); z
 
attributes(z)
attributes(z)$'scaled:center'
attributes(z)$'scaled:scale\'
 
attr(z,"scaled:center")
attr(z,"scaled:scale")
 
temp <- 2*1:10-1
attr(temp, "type") <- "arithmetic"
attr(temp, "initial") <- 1
attr(temp, "common difference") <- 2
temp
sum(temp)