[R] multiple tapply

Chuck Cleland ccleland at optonline.net
Thu Aug 7 14:01:54 CEST 2008


On 8/7/2008 7:01 AM, glaporta wrote:
> Hi folk,
> I tried this and it works just perfectly
> tapply(iris[,1],iris[5],mean)
> but, how to obtain a single table from multiple variables? 
> In tapply x is an atomic object so this code doesn't work 
> tapply(iris[,1:4],iris[5],mean)
> 
> Thanx and great summer holidays
> Gianandrea 

   Here is one way:

 > apply(iris[,1:4], 2, function(x){tapply(x, list(iris[,5]), mean)})

            Sepal.Length Sepal.Width Petal.Length Petal.Width
setosa            5.006       3.428        1.462       0.246
versicolor        5.936       2.770        4.260       1.326
virginica         6.588       2.974        5.552       2.026

   Here is another:

 > library(reshape)

 > iris.melt <- melt(iris, measure.var=names(iris)[1:4])

 > cast(iris.melt, variable + Species ~ ., mean)

        variable    Species (all)
1  Sepal.Length     setosa 5.006
2  Sepal.Length versicolor 5.936
3  Sepal.Length  virginica 6.588
4   Sepal.Width     setosa 3.428
5   Sepal.Width versicolor 2.770
6   Sepal.Width  virginica 2.974
7  Petal.Length     setosa 1.462
8  Petal.Length versicolor 4.260
9  Petal.Length  virginica 5.552
10  Petal.Width     setosa 0.246
11  Petal.Width versicolor 1.326
12  Petal.Width  virginica 2.026

-- 
Chuck Cleland, Ph.D.
NDRI, Inc. (www.ndri.org)
71 West 23rd Street, 8th floor
New York, NY 10010
tel: (212) 845-4495 (Tu, Th)
tel: (732) 512-0171 (M, W, F)
fax: (917) 438-0894



More information about the R-help mailing list