[R] why data.frame, mutate package and not lists

S Ellison S.Ellison at LGCGroup.com
Thu Sep 15 14:04:51 CEST 2016



>If you want
> to add variable to data.frame you have to use attach, detach. Right?

I'd have said "not at all", not "not quite". attach and detach have almost exactly nothing to do with adding to a data frame. 
You can add to a data frame using  
dfrm$newvar <- <something>
dfrm['newvar'] <- <something> 
cbind(dfrm, newvar=<something>) #adds a new variable called 'newvar'
rbind #to add rows
merge #to add columns and/or rows from another data frame
... and a few other things.

The only relevance of attach/detach is to do with the behaviour of attached objects, not to do with adding to data frames. If you have attach()ed something, changing the original object does not automatically update the copy of its variables in the current environment, or vice versa, because attach(), as documented, creates a _copy_. So _if_ you have attach()ed a data frame - or a list - you can't change the copy by changing the original object and you can't change the original object by changing the copy.  Only if you need to change both do you need to detach and reattach.

As a rule, I generally avoid attach() for that and other reasons (most of which are listed in ?attach). attach()is only sensible if you have already completed all the manipulation needed on the attached object first. Even then, using with() is safer.

S Ellison


*******************************************************************
This email and any attachments are confidential. Any use, copying or
disclosure other than by the intended recipient is unauthorised. If 
you have received this message in error, please notify the sender 
immediately via +44(0)20 8943 7000 or notify postmaster at lgcgroup.com 
and delete this message and any copies from your computer and network. 
LGC Limited. Registered in England 2991879. 
Registered office: Queens Road, Teddington, Middlesex, TW11 0LY, UK


More information about the R-help mailing list