Is there an easier way to access attributes of a class in R, can I use dot notation?

后端 未结 4 1829
暖寄归人
暖寄归人 2021-01-30 17:46

I have created an object in R that contains several attributes. How can I easily access them?

I can do:

attr(x, attributeName)

or:

4条回答
  •  不思量自难忘°
    2021-01-30 17:51

    attributes() returns a named list. I'd call it once and store them, then access via names. There is no point repeatedly calling either attr() or attributes() if you don't have to.

    x <- 1:10
    attr(x, "foo") <- "a"
    attr(x, "bar") <- "b"
    (features <- attributes(x))
    

    which gives:

    R> (features <- attributes(x))
    $foo
    [1] "a"
    
    $bar
    [1] "b"
    

    then access in the usual way

    R> features["foo"]
    $foo
    [1] "a"
    
    R> features$foo
    [1] "a"
    

提交回复
热议问题