how can I get the largest number of occurrences of unique values by group in R

For example, I have a dataframe that has been pivot_longer(). It contains the choice, the trial number and an ID.

ID trial choice
1   1   A
1   2   A
1   3   B
1   4   C
1   5   A
2   1   A
2   2   B
2   3   B
2   4   B
2   5   C
3   1   A
3   2   A
3   3   A
3   4   A
3   5   C
... 

How can I get the largest number of occurrences of unique values by group in R?

The ideal result should be like

ID max_choice max_time
1   A   3
2   B   3
3   A   4

Thank you for the help.

>Solution :

Using dplyr‘s count and slice_max you could do:

library(dplyr, warn = FALSE)

dat |>
  count(ID, choice) |>
  slice_max(n, by = ID)
#>   ID choice n
#> 1  1      A 3
#> 2  2      B 3
#> 3  3      A 4

Leave a Reply