How do I assign an attribute to a variable? For eg.
> x <- rpart(f.la, mydata)
assigns the attributes:
$names
[1] "frame" "where"
[3] "call" "terms"
[5] "cptable" "method"
[7] "parms" "control"
[9] "functions" "numresp"
[11] "splits" "variable.importance"
[13] "y" "ordered"
$xlevels
named list()
$ylevels
[1] "cancelled" "cart-abandon" "purchased" "returned"
$class
[1] "rpart"
Like this, I want to create attributes for a variable and assign a value to that attribute.
Alternatively to using
attributes
(see the answer by @CathG) you can useattr
. The first will work onNULL
objects but the second one won't. When you work with R attributes you have to remember there are not a simple as they look and can have some interesting side affects. Quick example:So far so good. Now lets set
dim
attributeclass
attribute is fundamental part of the S3 classes:Lets see what happens if we set attribute
class
as a'data.frame'
or we can define custom behavior (BTW this behavior is a reason why it is better to avoid dots when define functions):
Other attributes like
comment
andnames
have also special meaning and constraints. Take away message here is you have to a little bit careful when you work with attributes in R. One simple idea how to deal with is to use prefixes as artificial namespaces:In my opinion it particularly useful when you use third party libraries. Usage of the attributes is usually poorly documented, especially when used for some internal tasks, and it is pretty easy to introduce some hard to diagnose bugs if you use conflicting names.
If you have a variable :
you can do
or