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

huangapple go评论82阅读模式
英文:

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

问题

以下是翻译好的内容:

例如,我有一个已经使用pivot_longer()函数转换过的数据框。它包含选择(choice)、试验编号(trial)和一个ID。

如何在R中按组获取唯一值的最大出现次数?

理想的结果应该如下:

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

谢谢你的帮助。

英文:

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

  1. ID trial choice
  2. 1 1 A
  3. 1 2 A
  4. 1 3 B
  5. 1 4 C
  6. 1 5 A
  7. 2 1 A
  8. 2 2 B
  9. 2 3 B
  10. 2 4 B
  11. 2 5 C
  12. 3 1 A
  13. 3 2 A
  14. 3 3 A
  15. 3 4 A
  16. 3 5 C
  17. ...

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

The ideal result should be like

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

Thank you for the help.

答案1

得分: 0

使用dplyrcountslice_max,您可以执行以下操作:

  1. library(dplyr, warn = FALSE)
  2. dat %>%
  3. count(ID, choice) %>%
  4. slice_max(n, by = ID)
  5. #> ID choice n
  6. #> 1 1 A 3
  7. #> 2 2 B 3
  8. #> 3 3 A 4

请注意,这只是代码的中文翻译部分,不包括问题的回答。

英文:

Using dplyr's count and slice_max you could do:

  1. library(dplyr, warn = FALSE)
  2. dat |>
  3. count(ID, choice) |>
  4. slice_max(n, by = ID)
  5. #> ID choice n
  6. #> 1 1 A 3
  7. #> 2 2 B 3
  8. #> 3 3 A 4

huangapple
  • 本文由 发表于 2023年5月11日 06:11:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76222896.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定