Advertisement
hohiyan

fb-r-20230202

Feb 2nd, 2023 (edited)
976
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.57 KB | None | 0 0
  1. library(data.table)
  2.  
  3. # 原本的資料
  4. (md <- data.table(ID = rep(c("A", "B"), each=3),
  5.                  Subject = rep(c("English", "Math","Chinese"), 2),
  6.                  Grade = c(90, 80, 100, 70, 65, 80)))
  7. #>        ID Subject Grade
  8. #>    <char>  <char> <num>
  9. #> 1:      A English    90
  10. #> 2:      A    Math    80
  11. #> 3:      A Chinese   100
  12. #> 4:      B English    70
  13. #> 5:      B    Math    65
  14. #> 6:      B Chinese    80
  15.  
  16. md[, rank:=frank(-Grade), by=ID]
  17.  
  18. md
  19. #>        ID Subject Grade  rank
  20. #>    <char>  <char> <num> <int>
  21. #> 1:      A English    90     2
  22. #> 2:      A    Math    80     3
  23. #> 3:      A Chinese   100     1
  24. #> 4:      B English    70     2
  25. #> 5:      B    Math    65     3
  26. #> 6:      B Chinese    80     1
  27.  
  28.  
  29. # 當有科目同分時
  30. (md2 <- data.table(ID = rep(c("A", "B"), each=3),
  31.                  Subject = rep(c("English", "Math","Chinese"), 2),
  32.                  Grade = c(90, 90, 100, 70, 65, 65)))
  33. #>        ID Subject Grade
  34. #>    <char>  <char> <num>
  35. #> 1:      A English    90
  36. #> 2:      A    Math    90
  37. #> 3:      A Chinese   100
  38. #> 4:      B English    70
  39. #> 5:      B    Math    65
  40. #> 6:      B Chinese    65
  41.  
  42. md2[, rank:=frank(-Grade, ties.method = "dense"), by=ID]
  43. md2
  44. #>        ID Subject Grade  rank
  45. #>    <char>  <char> <num> <int>
  46. #> 1:      A English    90     2
  47. #> 2:      A    Math    90     2
  48. #> 3:      A Chinese   100     1
  49. #> 4:      B English    70     1
  50. #> 5:      B    Math    65     2
  51. #> 6:      B Chinese    65     2
  52.  
  53. <sup>Created on 2023-02-02 with [reprex v2.0.2](https://reprex.tidyverse.org)</sup>
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement