bubbalouie
bubbalouie

Reputation: 663

How to merge tapply() functions in R?

Input:

data(iris)
tapply(iris$Sepal.Length, iris$Species, mean)
tapply(iris$Sepal.Length, iris$Species, median)

Desired output: A dataset that shows the following

#setosa versicolor virginica
#5.006  5.936      6.588
#5.0    5.9        6.5

What is the best way to create a new, single dataset that includes the various tapply() outputs?

Upvotes: 1

Views: 1194

Answers (2)

LyzandeR
LyzandeR

Reputation: 37879

You can try this with one tapply call:

mat <-
do.call(cbind, 
        tapply(iris$Sepal.Length, iris$Species, function(x) c(mean(x), median(x)))
        )

Output:

> mat
     setosa versicolor virginica
[1,]  5.006      5.936     6.588
[2,]  5.000      5.900     6.500

Upvotes: 5

WhiteViking
WhiteViking

Reputation: 3201

Maybe like so:

data(iris)
x <- tapply(iris$Sepal.Length, iris$Species, mean)
y <- tapply(iris$Sepal.Length, iris$Species, median)
df <- rbind(x, y)
df

It yields

  setosa versicolor virginica
x  5.006      5.936     6.588
y  5.000      5.900     6.500

Upvotes: 1

Related Questions