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

r

Solution

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.

Problem

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

Original source