[R] Help on aggregate method
Erik Iverson
eriki at ccbr.umn.edu
Tue Jun 1 18:11:52 CEST 2010
Stella Pachidi wrote:
> Dear Erik and R experts,
>
> Thank you for the fast response!
>
> I include an example with the ChickWeight dataset:
>
> ap.dat <- ChickWeight
>
> matchMeanEx <- function(ind,dataTable,aggrTable)
> {
> index <- which((aggrTable[,1]==dataTable[["Diet"]][ind]) &
> (aggrTable[,2]==dataTable[["Chick"]][ind]))
> as.numeric(aggrTable[index,3])
> }
>
> avgW <- aggregate(ap.dat[["weight"]], by = list(ap.dat[["Diet"]],
> ap.dat[["Chick"]]), FUN="mean")
> meanW <- sapply((1:length(ap.dat[,1])), FUN=matchMeanEx, ap.dat, avgW)
> ap.dat <- cbind (ap.dat, meanW)
>
How about simply using ave.
ap.dat$meanW <- ave(ap.dat$weight, list(ap.dat$Diet, ap.dat$Chick))
More information about the R-help
mailing list