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

时间:2015-05-09 06:53:03

标签: r dataframe

我的数据框看起来像 -

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,然后选择出现频率最高的数字。

Id  Result
A    1
B    2
C    1  

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

4 个答案:

答案 0 :(得分:3)

您可以在这里一步使用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

答案 1 :(得分:1)

使用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

答案 2 :(得分: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

答案 3 :(得分:0)

使用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