Search code examples
rdata-analysis

calculate mode in R wrt other column


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


Solution

  • Using data.table library:

    library(data.table)
    
    dt <- as.data.table(df)
    dt[, .N, by = list(Col1, Col2)][, .SD[which.max(N)], by = Col1]