Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- library(data.table)
- # 原本的資料
- (md <- data.table(ID = rep(c("A", "B"), each=3),
- Subject = rep(c("English", "Math","Chinese"), 2),
- Grade = c(90, 80, 100, 70, 65, 80)))
- #> ID Subject Grade
- #> <char> <char> <num>
- #> 1: A English 90
- #> 2: A Math 80
- #> 3: A Chinese 100
- #> 4: B English 70
- #> 5: B Math 65
- #> 6: B Chinese 80
- md[, rank:=frank(-Grade), by=ID]
- md
- #> ID Subject Grade rank
- #> <char> <char> <num> <int>
- #> 1: A English 90 2
- #> 2: A Math 80 3
- #> 3: A Chinese 100 1
- #> 4: B English 70 2
- #> 5: B Math 65 3
- #> 6: B Chinese 80 1
- # 當有科目同分時
- (md2 <- data.table(ID = rep(c("A", "B"), each=3),
- Subject = rep(c("English", "Math","Chinese"), 2),
- Grade = c(90, 90, 100, 70, 65, 65)))
- #> ID Subject Grade
- #> <char> <char> <num>
- #> 1: A English 90
- #> 2: A Math 90
- #> 3: A Chinese 100
- #> 4: B English 70
- #> 5: B Math 65
- #> 6: B Chinese 65
- md2[, rank:=frank(-Grade, ties.method = "dense"), by=ID]
- md2
- #> ID Subject Grade rank
- #> <char> <char> <num> <int>
- #> 1: A English 90 2
- #> 2: A Math 90 2
- #> 3: A Chinese 100 1
- #> 4: B English 70 1
- #> 5: B Math 65 2
- #> 6: B Chinese 65 2
- <sup>Created on 2023-02-02 with [reprex v2.0.2](https://reprex.tidyverse.org)</sup>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement