Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)?

like image 498
RockScience Avatar asked Jun 23 '11 05:06

RockScience


People also ask

How do you access attributes of a class?

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.

What does class () do in R?

The class() function in R is used to return the values of the class attribute of an R object.


1 Answers

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" 
like image 91
Gavin Simpson Avatar answered Sep 19 '22 17:09

Gavin Simpson