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

查看:589
本文介绍了如何在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\n")
> 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天全站免登陆