Skip to content
Prev 266261 / 398503 Next

Mean and Timeseries modelling

Hi:
On Fri, Jul 22, 2011 at 2:28 AM, Marko <markho1984 at googlemail.com> wrote:
Other ways to do this, which output data frames rather than matrices,
would include

# the formula interface below works with R-2.11.0 +
aggregate(value ~ a + typ, data = df, FUN = mean)

library(plyr)
ddply(df, .(a, typ), summarise, m = mean(value))

Both would give you the 'long form' of the data. One could use the
cast() function in the reshape[2] package or the reshape() function
from the base package to convert it to 'wide' form.
It sounds like you want something like ave(). One approach (untested)
might be as follows:

ddply(df, .(a, typ), transform, mean_typ_year = mean(value))

You may want to re-sort the data afterward because ddply() will sort
by a x typ combinations rather than a x m x d. You could also use the
transform() function, perhaps something like

transform(df, mean_typ_year = ave(value, list(a, typ), FUN = mean))

##------
Here's a toy example to illustrate:

df <- data.frame(a = factor(rep(LETTERS[1:3], each = 6)),
                  b = factor(rep(letters[1:3], each = 2)),
                  d = rep(1:6, 3),
                  val = rnorm(18, m = 40))
library('plyr')
ddply(df, .(a, b), transform, m = mean(val))
transform(df, m = ave(val, list(a, b), FUN = mean))

HTH,
Dennis