在 R 中计算其他列的模式

calculate mode in R wrt other column

此问题与以下问题不重复: 是否有用于查找模式的内置函数? Is there a built-in function for finding the mode? 上面提到的所有答案 link 查找单列或向量的模式。而我想找到其他列的模式

我有这样的数据:-

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

我想找到模式,结果应该如下所示:-

col1  Mode 
B     Small
C     Medium
D     High

有什么帮助吗?

谢谢

使用 data.table 库:

library(data.table)

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

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

非常相似的解决方案,就留在这里供参考。