Andrey wrote on 10/13/2011 08:40:21 AM:
> 
>  Dear All,
> 
>  For a vector, I use this
> 
>   xu<-1:20
>   t<-rep((1:4),each=5)
>   tapply(xu,t,mean)
>   1  2  3  4
>   3  8 13 18
> 
>  and for a matrix the only way I may guess is:
>  > xu
>       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
>  [1,]    1    4    3    2    1    4    3    2
>  [2,]    2    1    4    3    2    1    4    3
>  [3,]    3    2    1    4    3    2    1    4
>  [4,]    1    4    3    2    1    4    3    2
>  [5,]    2    1    4    3    2    1    4    3
>  [6,]    3    2    1    4    3    2    1    4
> > t
>  [1] 1 1 1 2 2 2
> > y
>         [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
>  [1,]    0    0    0    0    0    0    0    0
>  [2,]    0    0    0    0    0    0    0    0
> 
>  > for (i in 1:dim(xu)[2]) y[,i]<-tapply(xu[,i],t,mean)
>  > y
>         [,1]        [,2]         [,3]  [,4] [,5]         [,6] [,7]
> [,8]
>  [1,]    2 2.333333 2.666667    3    2 2.333333 2.666667    3
>  [2,]    2 2.333333 2.666667    3    2 2.333333 2.666667    3
> 
> I do not like the need to create a matrix (y) for the result.
> Is there a better way?
> 
> Thanks,
> Andrei.


apply(xu, 2, tapply, t, mean)

Jean
	[[alternative HTML version deleted]]

