Why is names(x) better than attr(x, “names”)?

后端 未结 1 1511
伪装坚强ぢ
伪装坚强ぢ 2021-01-18 04:53

I am reading an Advanced R topic on data structures and attributes. It says:

You should always get and set these attributes with their accessor func

相关标签:
1条回答
  • 2021-01-18 05:07

    You shouldn't access attributes directly because the author of code should provide an API for you to use to access them. That gives them the flexibility to change the underlying code without changing the API.

    The xts package provides a good example of this:

    > library(xts)
    > x <- xts(1:3, as.POSIXct("2014-01-01")+0:2)
    > index(x)
    [1] "2014-01-01 00:00:00 CST" "2014-01-01 00:00:01 CST" "2014-01-01 00:00:02 CST"
    > attr(x, "index")
    [1] 1388556000 1388556001 1388556002
    attr(,"tzone")
    [1] ""
    attr(,"tclass")
    [1] "POSIXct" "POSIXt"
    

    At one point in the past, the internal index was stored as POSIXct, but we changed the underlying structure for performance reasons. You can see that the public API didn't change, however.

    0 讨论(0)
提交回复
热议问题