如何在R中设置变量的属性?

Sha*_*mar 10 attributes r

如何为变量分配属性?例如.

> x <- rpart(f.la, mydata) 
Run Code Online (Sandbox Code Playgroud)

分配属性:

$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"
Run Code Online (Sandbox Code Playgroud)

像这样,我想为变量创建属性并为该属性赋值.

zer*_*323 17

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

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

到现在为止还挺好.现在让我们设置dim属性

> 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
Run Code Online (Sandbox Code Playgroud)

class属性是S3类的基本部分:

> foo <- list()
> foo
list()
Run Code Online (Sandbox Code Playgroud)

让我们看看如果我们将属性设置class为a 会发生什么'data.frame'

> attr(foo, 'class') <- 'data.frame'
> foo
data frame with 0 columns and 0 rows
Run Code Online (Sandbox Code Playgroud)

或者我们可以定义自定义行为(BTW这种行为是为什么在定义函数时最好避免点的原因):

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

其他属性喜欢commentnames具有特殊含义和约束.在这里删除消息当你使用R中的属性时你必须要小心.一个简单的想法如何处理是使用前缀作为人工命名空间:

> 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
Run Code Online (Sandbox Code Playgroud)

在我看来,当你使用第三方库时它特别有用.对属性的使用通常很难记录,特别是当用于某些内部任务时,如果使用冲突的名称,很容易引入一些难以诊断的错误.


Cat*_*ath 9

如果你有一个变量:

x<-"some variable"
Run Code Online (Sandbox Code Playgroud)

你可以做

attributes(x)$myattrib<-"someattributes"

> x
[1] "some variable"
attr(,"myattrib")
[1] "someattributes"
Run Code Online (Sandbox Code Playgroud)

要么

> attributes(x)
$myattrib
[1] "someattributes"
Run Code Online (Sandbox Code Playgroud)