I have created an object in R that contains several attributes. How can I easily access them?
I can do:
attr(x, attributeName)
or:
attributes(x)$attributeName
but none of them is really convenient.
Is there a quicker way (like the dot in C++ or Java)?
Accessing the attributes of a class To check the attributes of a class and also to manipulate those attributes, we use many python in-built methods as shown below. getattr() − A python method used to access the attribute of a class. hasattr() − A python method used to verify the presence of an attribute in a class.
The class() function in R is used to return the values of the class attribute of an R object.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With