What is the attr() function in R?
Overview
The attr() function in R is used to determine or set a specific attribute of an object.
Syntax
attr(x, which, exact = FALSE)
attr(x, which) <- value
Parameters
The attr() function takes the following parameter values:
x: This represents an object whose attributes are to be accessed.which: This represents a non-empty character string that specifies which attribute is to be accessed.exact: This takes a logical value of whether thewhichvalue should be matched exactly or not.value: This represents the new value of the attribute.
Code example
# creating an objectx <- 1:8# setting a 2 by 4 matrix as an attribute to xattr(x,"dim") <- c(2, 4)# printing xx
Code explanation
-
Line 2: We specify that
xhas numeric values starting from1and ending at8. -
Line 5: We define a
2by4matrix as an attribute tox, using theattr()function. -
Line 8: We print the value of
x.