0

I have the following data:

I have a data.frame and I need to calculate the mean per a_id and b_id.

a_id      b_id  Rate1     Rate2
A          1      12        23
A          0      18        73
A          1      19        45
B          1      53        19
B          0      22        87
B          0      19        45
C          1      22        87
C          0      67        43
C          1      45        32

My desired output is like below

a_id      b_id   Rate1
A          1      15.5
A          0      18  

B          1      53  
B          0      20.5

C          1      22  
C          0      33.5
Jj Blevins
  • 355
  • 1
  • 13
  • Maybe something like `df %>% group_by(a_id, b_id) %>% summarize(mean = mean(Rate1))` – Matt Jul 19 '19 at 19:28
  • 1
    Almost every method at the FAQ works as well for multiple grouping columns as for one. In base R, I'd recommend `aggregate(Rate1 ~ a_id + b_id, your_data, mean)`. Or `data.table` and `dplyr` packages also make this simple. – Gregor Thomas Jul 19 '19 at 19:31

1 Answers1

1

You can do this with aggregate.

aggregate(df$Rate1, df[,1:2], mean)
  a_id b_id    x
1    A    0 18.0
2    B    0 20.5
3    C    0 67.0
4    A    1 15.5
5    B    1 53.0
6    C    1 33.5
G5W
  • 36,531
  • 10
  • 47
  • 80