On Tue, Jun 16, 2009 at 5:16 AM, Stefan Uhmann <stefan.uhmann@googlemail.com
> wrote:

> why does this not work?
>
> df <- data.frame(var1 = c(3,2,1), var2 = c(6,5,4), var3 = c(9,8,7),
>        fac = c('A', 'A', 'B'))
> tapply(cbind(df$var1, df$var2, df$var3), df$fac, mean)
>

Because tapply is defined for atomic vectors and not for data frames.  Why?
I don't know.

Does this do what you want?:

> df <- data.frame(var1 = c(3,2,1), var2 = c(6,5,4), var3 = c(9,8,7))
> fac <- c('a','a','b')
> do.call(rbind, lapply(split(df,fac),mean))
  var1 var2 var3
a  2.5  5.5  8.5
b  1.0  4.0  7.0

Alternatively, you can use sapply, which returns the result in matrix form.

> sapply(split(df,fac),mean)
       a b
var1 2.5 1
var2 5.5 4
var3 8.5 7
> as.data.frame(t(sapply(split(df,fac),mean)))
  var1 var2 var3
a  2.5  5.5  8.5
b  1.0  4.0  7.0

Note that sapply's matrix output form (the so-called 'simplification') needs
to be transposed.

             -s

	[[alternative HTML version deleted]]


