Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading