How to merge tapply() functions in R?

时间:2015-09-01 22:22:43

标签: r dataset tapply

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?

2 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:1)

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