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

后端 未结 4 1931
暖寄归人
暖寄归人 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 18:00

    Don't use attributes for your object, use a list:

    myobj <- structure(list(a = 1, b = 2), class = "myclass")
    print.myclass <- function(x, ...) cat("A: ", x$a, " B: ", x$b, "\n", sep = "")
    myobj
    

    Of course, this might not work if you're extending an existing object (e.g. vector), but in my experience it's a generally better way to build objects.

提交回复
热议问题