Aggregate funds and maintain N

I'm trying aggregate

a dataset, but I want to store the number of observations as well. So what I have looks like this:

aggregate(iris$Sepal.Length, by=list(iris$Species), FUN=mean)

      

But this returns an object like this:

 Group.1     x
1     setosa 5.006
2 versicolor 5.936
3  virginica 6.588

      

when I want AND and the number of cases (rows) in each group (in a separate column)

+3


source to share


2 answers


Trial and error showed it works:

FUN = function(x) c(m = mean(x), n = length(x))

      



There are other ways to do this in packages like dplyr and data.table.

+6


source


dplyr and hadley ftw



grp <- group_by(iris, Species)
summarise(grp, avg = mean(Sepal.Length), n =n ())

Source: local data frame [3 x 3]
     Species   avg  n
1     setosa 5.006 50
2 versicolor 5.936 50
3  virginica 6.588 50

      

+2


source







All Articles