Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

aggregate means and keep N

Tags:

r

aggregate

I'm trying to aggregate a dataset, but I want to also keep the number of observations. So what I have is similar to this:

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

But that returns an object like so:

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

when what I want is that AND the number of observations (rows) in each group (in a separate column)

like image 608
Alex Avatar asked Jan 28 '26 12:01

Alex


1 Answers

Trial and error revealed that this 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.

like image 72
Frank Avatar answered Jan 30 '26 03:01

Frank



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!