[R] more flexible "ave"

Patrick Hausmann patrick.hausmann at uni-bremen.de
Tue Nov 30 15:42:04 CET 2010


Hi all,

I would like to calculate the percent of the total per group for this 
data.frame:

df <- data.frame(site = c("a", "a", "a", "b", "b", "b"),
                  gr = c("total", "x1", "x2", "x1", "total","x2"),
                  value1 = c(212, 56, 87, 33, 456, 213))
df

calcPercent <- function(df) {

     df <- transform(df, pct_val1 = ave(df[, -c(1:2)], df$gr,
                               FUN = function(x)
                               x/df[df$gr == "total", "value1"]) )
}

# This works as intended...
w <- lapply(split(df, df$site), calcPercent)
w <- do.call(rbind, w)
w

# ... but when I add a new column
df$value2 <- c(1546, 560, 543, 234, 654, 312)

# the result is not what I want...
w <- lapply(split(df, df$site), calcPercent)
w <- do.call(rbind, w)
w

Clearly I have to change the function, (particularly "value1") - but 
how... I've also played around with "apply" but without any success.

Thanks for any help!
Patrick



More information about the R-help mailing list