Return most frequent string value for each group [duplicate]

旧巷老猫 提交于 2019-11-30 01:49:39

The key is to start grouping by both a and b to compute the frequencies and then take only the most frequent per group of a, for example like this:

df %>% 
  count(a, b) %>%
  slice(which.max(n))

Source: local data frame [2 x 3]
Groups: a

  a b n
1 1 B 2
2 2 B 2

Of course there are other approaches, so this is only one possible "key".

by() each value of a, create a table() of b and extract the names() of the largest entry in that table():

> with(df,by(b,a,function(xx)names(which.max(table(xx)))))
a: 1
[1] "B"
------------------------
a: 2
[1] "B"

You can wrap this in as.table() to get a prettier output, although it still does not exactly match your desired result:

> as.table(with(df,by(b,a,function(xx)names(which.max(table(xx))))))
a
1 2 
B B

What works for me or is simpler is:

df %>% group_by(a) %>% slice(which.max(table(b)) )
df %>% group_by(a) %>% count(b) %>% top_n(1)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!