【问题标题】:How to set attributes for a variable in R?如何为R中的变量设置属性?
【发布时间】:2014-12-18 12:44:03
【问题描述】:

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

> 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"

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

【问题讨论】:

    标签: r attributes


    【解决方案1】:

    除了使用attributes (see the answer by @CathG),您还可以使用attr。第一个将适用于NULL 对象,但第二个不会。当您使用 R 属性时,您必须记住它们看起来并不简单,并且可能会产生一些有趣的副作用。快速示例:

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

    到目前为止一切顺利。现在让我们设置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
    

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

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

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

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

    或者我们可以定义自定义行为(顺便说一句,这种行为是定义函数时最好避免使用点的原因):

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

    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
    

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

    【讨论】:

      【解决方案2】:

      如果你有一个变量:

      x<-"some variable"
      

      你可以的

      attributes(x)$myattrib<-"someattributes"
      
      > x
      [1] "some variable"
      attr(,"myattrib")
      [1] "someattributes"
      

      > attributes(x)
      $myattrib
      [1] "someattributes"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-10-31
        • 2021-12-31
        • 2013-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多