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

Douglas Bates bates at stat.wisc.edu
Thu Sep 23 23:20:38 CEST 2010


On Thu, Sep 23, 2010 at 3:48 PM, Tyler Smith <tyler.smith at eku.edu> wrote:
>  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.

Most people prefer the $ operator because it is easier to type and you
don't need to quote the name.  The expression

fr$x

is simpler to type and probably to understand than is

fr[["x"]]

However, it is good to know that "[[]]" can be used because it is the
answer to a frequent question from beginners, which is "How do I pass
the name of the variable into a function?".  They will often try

meanMed <- function(frm, nm) c(mean=mean(frm$nm), median=median(frm$nm))

and are frustrated that it doesn't work as intended.  If you want to
use the value of the argument called nm as the name of the variable to
extract you must use frm[[nm]]




More information about the R-sig-teaching mailing list