0

This question is not duplicate of following question : Is there a built-in function for finding the mode? Is there a built-in function for finding the mode? All the answers mentioned on above link find mode for a single column or a vector. Whereas I want to find mode wrt to other column

I have data like this :-

Col1 Col2
C    High
B    Small
C    Medium
B    High
D    Medium
B    Medium
B    Small
B    Medium
B    Small
B    High
B    Small
C    Medium
B    Medium
D    High
B    Small
B    High
D    High

I want to find mode and result should look as follows:-

col1  Mode 
B     Small
C     Medium
D     High

Any help?

Thanks

Community
  • 1
  • 1
r4sn4
  • 117
  • 5
  • 14
  • Could you explain a bit more what you actually try to achieve? I can't understand how you got that result without further explanation. – SaschaM78 Feb 25 '16 at 09:53
  • which value from col2 occurs maximum number of time for each unique value in col1. Like for B, Value small occurred maximum number of times . Similarly for C and D – r4sn4 Feb 25 '16 at 10:11

2 Answers2

3
library(data.table)
df[,.(Mode = names(which.max(table(Col2)))), by = Col1]

   Col1   Mode
1:    C Medium
2:    B  Small
3:    D   High

Very similar solution, will just leave it here for reference.

Jaap
  • 81,064
  • 34
  • 182
  • 193
statespace
  • 1,644
  • 17
  • 25
2

Using data.table library:

library(data.table)

dt <- as.data.table(df)
dt[, .N, by = list(Col1, Col2)][, .SD[which.max(N)], by = Col1]
danas.zuokas
  • 4,551
  • 4
  • 29
  • 39