Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...