How to set attributes for a variable in R?

2020-06-03 00:58发布

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.

标签: r attributes
2条回答
▲ chillily
2楼-- · 2020-06-03 01:54

Alternatively to using attributes (see the answer by @CathG) you can use attr. The first will work on NULL 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:

> x <- 1:10
> class(x)
[1] "integer"
> x
 [1]  1  2  3  4  5  6  7  8  9 10

So far so good. Now lets set dim attribute

> attr(x, 'dim') <- c(2, 5)
> class(x)
[1] "matrix"
> x
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    3    5    7    9
[2,]    2    4    6    8   10

class attribute is fundamental part of the S3 classes:

> foo <- list()
> foo
list()

Lets see what happens if we set attribute class as a 'data.frame'

> attr(foo, 'class') <- 'data.frame'
> foo
data frame with 0 columns and 0 rows

or we can define custom behavior (BTW this behavior is a reason why it is better to avoid dots when define functions):

> print.foo <- function(x) cat("I'm foo\n")
> attr(foo, 'class') <- 'foo'
> foo
I'm foo

Other attributes like comment and names 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:

> x <- 1:10
> attr(x, 'zero323.dim') <- c(2, 5)
> class(x)
[1] "integer"
> x
[1]  1  2  3  4  5  6  7  8  9 10
attr(, 'zero323.dim')
[1] 2 5

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.

查看更多
Animai°情兽
3楼-- · 2020-06-03 01:55

If you have a variable :

x<-"some variable"

you can do

attributes(x)$myattrib<-"someattributes"

> x
[1] "some variable"
attr(,"myattrib")
[1] "someattributes"

or

> attributes(x)
$myattrib
[1] "someattributes"
查看更多
登录 后发表回答