[R] aggregate.formula: formula from string

Thaler,Thorn,LAUSANNE,Applied Mathematics Thorn.Thaler at rdls.nestle.com
Wed Oct 31 10:46:19 CET 2012

Dear all,

I want to use aggregate.formula to conveniently summarize a data.frame. I have quiet some variables in the data.frame and thus I don't want to write all these names by hand, but instead create them on the fly. This approach has the advantage that if there will be even more columns in the data.frame I don't have to change the code.

I've hence tried to construct a formula object and to pass that to aggregate:

d <- expand.grid(a = factor(1:3), b = factor(LETTERS[1:2]))
d <- rbind(d,d,d)
d$y <- rnorm(18)
d$z <- rnorm(18)
mF <- as.formula(paste("cbind(", paste(names(d)[-(1:2)], collapse = ","), ") ~ a + b", sep = ""))

But if I try to pass that formula to aggregate

aggregate(mF, d, mean)

I get the following error:

Error in m[[2L]][[2L]] : object of type 'symbol' is not subsettable

But if I pass the formula directly:

aggregate(cbind(y, z) ~ a + b, d, mean)

Everything is working as expected.

So I was wondering what went wrong? I know I could use a formula like . ~ a + b instead and this would work fine, but I'm just interested in why the outlined approach does not work as expected, and where my mistake lies? (that means in particular I am not asking for a solution of how to get the thing done - there are plenty of alternatives - but instead to understand why this very approach does not work)

Thanks for your help!

Kind Regards,

Thorn Thaler

Applied Mathematics 
Nestec Ltd,
Nestlé Research Center
PO Box 44 
CH-1000 Lausanne 26
Phone: +41 21 785 8220
Fax: +41 21 785 9486

More information about the R-help mailing list