Skip to content
Prev 82840 / 398503 Next

Looking for a sort of tapply() to data frames

On 12/15/05, January Weiner <january at uni-muenster.de> wrote:
You don't get them as a column but you get them as the
component labels.

   by(df, df$Day, function(x) colMeans(x[,-1]))

If you convert it to a data frame you get them as the rownames:

  do.call("rbind", by(df, df$Day, function(x) colMeans(x[,-1])))
I think you want class(df) which shows its a data frame.
df[,1] and df$Day both refer to the same first column.
aggregate(df[,-1], df[,1,drop = FALSE], mean)

or

   aggregate(df[,-1], list(Day = df$Day), mean)

The second arg of aggregate must be a list which is why we used
drop = FALSE in the first instance and an explicit list in the second.

Another alternative is to use summaryBy from the doBy package found
at http://genetics.agrsci.dk/~sorenh/misc/ :

   library(doBy)
   summaryBy(cbind(var1, var2) ~ Day, data = df)
do.call("rbind", ddf)