Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a reason to prefer extractor functions to accessing attributes with $?

Tags:

On a thread on CrossValidated, I made the following comment:

I suspect this is actually an R question about the difference between working with S3 classes (that are accessed via $) & S4 classes (that are accessed via @)...

@Gavin Simpson subsequently commented:

@gung is more than likely spot on, but the solution is probably not to delve into objects and rip out whatever you feel but to learn to use extractor functions, in this case coefficients() or its shorter alias coef(), as in coef(fit)

I'm intrigued by this. Why would using coef(model) be better than model$coefficients[,1], for example? (I recognize that the latter is uglier and requires slightly more typing, but I doubt that's the reason intended.) What about the case where there isn't an existing extractor function (e.g., accessing the t-statistics)?

like image 836
gung - Reinstate Monica Avatar asked Jul 24 '13 02:07

gung - Reinstate Monica


2 Answers

Because then the author of the package you are using is free to change the underlying structure of the model object without worrying about breaking everyone's code.

Obviously this generalizes to R Core as well. It is recommended to use those extractor functions because then you can be sure that it will always return the correct information, even if the function authors find it necessary to shuffle things around under the hood.

Maybe they add some more information to one of the elements of the model list object, and that changes the order of everything? All your code will break.

like image 120
joran Avatar answered Sep 22 '22 06:09

joran


The other main reason is that you have to be careful what you get. For example, what do you get if you do

mod <- glm(y ~ x1 + x2, data = foo, family = binomial) mod$residuals 

?? (Hover below for Answer if you don't know!)

You get working residuals which probably aren't very useful to many people

The extractor function knows about this and will return something useful or allow the use to extract different aspects of the sought component.

I always tell people I teach R to that they shouldn't use $ or @ unless they are very familiar with the method and object being accessed, and never in production code - you are just asking for trouble if you do.

like image 23
Gavin Simpson Avatar answered Sep 22 '22 06:09

Gavin Simpson