How can I calculate mean per group in a data frame

449    Asked by AyushiKhatri in Java , Asked on Apr 22, 2021
Answered by Ben PHILLIPS

To calculate the mean of grouped data, the first step is to determine the midpoint (also called a class mark) of each interval, or class. These midpoints must then be multiplied by the frequencies of the corresponding classes. The sum of the products divided by the total number of values will be the value of the mean.


To calculate mean in r by group

Mean by group (A, B, C):

A(mean) = Sum/Number of terms = 20/3 = 6.67.

B(mean) = Sum/Number of terms = 14/3 = 4.67.

C(mean) = Sum/Number of terms = 8/3 = 2.67.

You can use aggregate function for calculating mean per group.

aggregate(d[, a:b], list(d$Name), mean)

Here we will calculate the aggregate of some columns a and b of dataframe d, grouping by d$Name, and applying the mean function.



Your Answer

Interviews

Parent Categories