从可用结果中查找最大出现次数

Finding the max number of occurrences from the available result

我有一个数据框,看起来像 -

Id  Result
A    1
B    2
C    1
B    1
C    1
A    2
B    1
B    2
C    1
A    1
B    2

现在我需要计算每个 Id 有多少个 1 和 2,然后 select 计算出现频率最大的数字。

Id  Result
A    1
B    2
C    1  

我该怎么做?我曾尝试以某种方式使用 table 函数,但无法有效地使用它。任何帮助,将不胜感激。

data.table你可以试试(df是你的data.frame):

require(data.table)
dt<-as.data.table(df)
dt[,list(times=.N),by=list(Id,Result)][,list(Result=Result[which.max(times)]),by=Id]
#   Id Result
#1:  A      1
#2:  B      2
#3:  C      1

这里可以一步使用aggregate

df <- structure(list(Id = structure(c(1L, 2L, 3L, 2L, 3L, 1L, 2L, 2L, 
3L, 1L, 2L), .Label = c("A", "B", "C"), class = "factor"), 
Result = c(1L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 2L)),
.Names = c("Id", "Result"), class = "data.frame", row.names = c(NA, -11L)
)

res <- aggregate(Result ~ Id, df, FUN=function(x){which.max(c(sum(x==1), sum(x==2)))})
res

结果:

  Id Result
1  A      1
2  B      2
3  C      1

使用dplyr,你可以试试

library(dplyr)
df %>% group_by(Id, Result) %>% summarize(n = n()) %>% group_by(Id) %>%
  filter(n == max(n)) %>% summarize(Result = Result)


  Id Result
1  A      1
2  B      2
3  C      1

使用 tableave

的选项
subset(as.data.frame(table(df1)),ave(Freq, Id, FUN=max)==Freq, select=-3)
#   Id Result
# 1  A      1
# 3  C      1
# 5  B      2