[R] dynamic list in aggregate()

William Dunlap wdunlap at tibco.com
Fri Aug 31 05:19:53 CEST 2012


Replace
   lst <- paste('dat$', grp, sep='', collapse =',')
   aggregate(dat$x, list(lst), mean)
with
   aggregate(dat$x, dat[grp], mean)
The 'by' argument to aggregate should be a list
and data.frames (like dat and dat[grp]) are lists.


Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf
> Of Xianming Wei
> Sent: Thursday, August 30, 2012 7:37 PM
> To: r-help at r-project.org
> Subject: [R] dynamic list in aggregate()
> 
> Hi all,
> 
> How can I have a dynamic list for different combinations of grouping factors in the
> following example? Thanks.
> 
> dat <- data.frame(x=rnorm(100),
>                   a=sample(letters[1:5], replace = T),
>                   b=sample(letters[1:5], replace = T),
>                   c=sample(letters[1:5], replace = T),
>                   d=sample(letters[1:5], replace = T))
> 
> ## define grouping factors
> grp <- c('a','d') # or any combination among a, b, c and d
> ## something like this for the list
> lst <- paste('dat$', grp, sep='', collapse =',')
> ## aggregate on the defined list
> aggregate(dat$x, list(lst), mean)
> 
> Thanks.
> 
> Regards,
> Xianming
> 
> 
> -------------------- Internet e-Mail Disclaimer --------------------
> 
> PRIVILEGED - PRIVATE AND CONFIDENTIAL: This email and any files transmitted with it
> are intended solely for the use of the addressee(s) and may contain information, which is
> confidential or privileged. If you are not the intended recipient, be aware that any
> disclosure, copying, distribution, or use of the contents of this information is prohibited.
> In such case, you should destroy this message and kindly notify the sender by reply e-
> mail. The views and opinions expressed in this e-mail are those of the sender and do not
> necessarily reflect the views of the company.
> 
> VIRUSES:  Email transmission cannot be guaranteed to be secure or error free, as
> information may be intercepted, corrupted, lost, destroyed, arrive late or incomplete or
> contain viruses. This email and any files attached to it have been checked with virus
> detection software before transmission. You should nonetheless carry out your own virus
> check before opening any attachment. BSES Limited does not represent or warrant that
> files attached to this email are free from computer viruses or other defects and accepts
> no liability for any loss or damage that may be caused by software viruses
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list