[R-sig-teaching] pros/cons of teaching attach()

Greg Snow Greg.Snow at imail.org
Fri Sep 24 22:16:37 CEST 2010


I think that the reference to not using $ or [[ was meant for cases where there is a proper extraction function, residuals being the example used.

If "fit" is an lm object then I could plot the fitted vs. residuals plot like this:

> plot( fit$fitted, fit$residuals )

Or like this:

> plot( fitted(fit), resid(fit) )

The second one is preferred as it properly extracts the information without needing to know the exact contents of fit (and the axis limits look a little nicer). 

With an lm object the 2 plots will be essentially the same, but what if fit is a glm object?  Then fit$residuals does give something that fits the definition of residuals, but of the different types of residuals available for glm fits, this gives the one that is least interesting/interpretable to humans (they were useful to the program for getting the fit).  Here the resid (or residuals) function defaults to a more meaningful set of residuals and gives options for other types.

If we have arbitrary objects without extractor functions then we need to use $ or [[ to extract the individual elements, but when working with fitted objects it is much better to teach students to use the proper extractor functions rather than directly working with elements of the object itself.

-- 
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at imail.org
801.408.8111

> -----Original Message-----
> From: r-sig-teaching-bounces at r-project.org [mailto:r-sig-teaching-
> bounces at r-project.org] On Behalf Of Tyler Smith
> Sent: Thursday, September 23, 2010 2:49 PM
> To: r-sig-teaching at r-project.org
> Subject: Re: [R-sig-teaching] pros/cons of teaching attach()
> 
>   On 09/22/2010 04:36 AM, Gavin Simpson wrote:
> >
> > I don't use attach() at all; too easy to make mistakes that are
> > difficult to track down. I tend not to use $ either as that
> encourages
> > people to use it to go fiddling in the bowels of other lists
> (objects);
> > model$residuals might be OK for lm() models (though not if you've
> used
> > na.exclude for example) but students might be surprised with what
> they
> > get with more complex modelling functions with different residuals.
> >
> This is going to be a dumb question, but what do you use instead of $
> for accessing variables in a list? [[]] allows for the same fiddling.
> 
> Thanks,
> 
> Tyler
> 
> _______________________________________________
> R-sig-teaching at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-sig-teaching




More information about the R-sig-teaching mailing list