[R] dynamic list in aggregate()

arun smartpink111 at yahoo.com
Fri Aug 31 14:07:31 CEST 2012


HI,

You can also use these in addition to aggregate:
tapply(dat$x,INDEX=dat[grp],mean)
library(plyr)
ddply(dat,.(dat[grp]$a,dat[grp]$d),summarize,mean(x))
#  dat[grp]$a dat[grp]$d         ..1
#1          b          c  0.26781378
#2          b          d -0.01994023
#3          c          e  0.14874737
#4          d          d -0.21051512
#5          e          b  0.18821072

A.K.



----- Original Message -----
From: Xianming Wei <XWei at bses.com.au>
To: "r-help at r-project.org" <r-help at r-project.org>
Cc: 
Sent: Thursday, August 30, 2012 10:37 PM
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