如何为R中的变量设置属性? [英] How to set attributes for a variable in R?

查看:19
本文介绍了如何为R中的变量设置属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将属性分配给变量?例如.

How do I assign an attribute to a variable? For eg.

> x <- rpart(f.la, mydata) 

分配属性:

$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.

推荐答案

替代使用 attributes (见@CathG 的答案)你可以使用 attr.第一个将适用于 NULL 对象,但第二个不会.当您使用 R 属性时,您必须记住它们看起来并不简单,并且可能会产生一些有趣的副作用.快速示例:

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

到目前为止一切顺利.现在让我们设置 dim 属性

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 属性是 的基本部分S3 类:

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

让我们看看如果我们将属性 class 设置为 'data.frame'

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
")
> attr(foo, 'class') <- 'foo'
> foo
I'm foo

commentnames 等其他属性也有特殊含义和约束.这里的要点是,当您在 R 中使用属性时,您必须小心一点.如何处理的一个简单想法是使用前缀作为人工命名空间:

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.

这篇关于如何为R中的变量设置属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆