Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)

I have a data.frame and I need to calculate the mean per group (i.e. per Month, below).

Name     Month  Rate1     Rate2

Aira       1      12        23

Aira       2      18        73

Aira       3      19        45

Ben        1      53        19

Ben        2      22        87

Ben        3      19        45

Cat        1      22        87

Cat        2      67        43

Cat        3      45        32

My desired output is like below, where the values for Rate1 and Rate2 are the group means. Please disregard the value, I have made it up for the example.

Name       Rate1       Rate2

Aira        23.21       12.2

Ben         45.23       43.9

Cat         33.22       32.2

1 Answer

0 votes
by

To find the mean of columns by group, use the aggregate function as follows:

df <- data.frame(Name = c("Aira", "Aira", "Aira", "Ben", "Ben", "Ben", "Cat", "Cat", "Cat"), 

                       Month = c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), 

                       Rate1 = c(15, 2, 6, 2, 34, 3, 29, 17, 10),

                       Rate2 = c(17, 5, 8, 5, 3, 17, 16, 2, 15))

aggregate(df[, 3:4], list(df$Name), mean)

Here, in the aggregate function, we have selected column 3&4, grouped them by “Name”, and applied the mean function to the grouped columns.

Output:

  Group.1     Rate1     Rate2

1    Aira  7.666667 10.000000

2     Ben 13.000000  8.333333

3     Cat 18.666667 11.000000

Related questions

Browse Categories

...