I am trying to find the most frequent value by group. In the following example dataframe:
df<-data.frame(a=c(1,1,1,1,2,2,2,3,3),b=c(2,2,1,2,3,3,1,1,2))
> df
a b
1 1 2
2 1 2
3 1 1
4 1 2
5 2 3
6 2 3
7 2 1
8 3 1
9 3 2
I would like to add a column 'c' which has the most occurring value in 'b' when its values are grouped by 'a'. I would like the following output:
> df
a b c
1 1 2 2
2 1 2 2
3 1 1 2
4 1 2 2
5 2 3 3
6 2 3 3
7 2 1 3
8 3 1 1
9 3 2 1
I tried using table and tapply but didn't get it right. Is there a fast way to do that?
Thanks!