有没有办法根据分组项目在该组中的顺序为分组项目编制索引?
Is there a way to index numbers for grouped items according to their order in that group?
我有一个标题或数据框如下:
tib <- tibble(PlayerName=c("P1","P2","P3","P1","P2","P3"), GameNo=c(1,1,1,2,2,2), PlayerScore=c(10,15,9,8,12,18))
所以,我想做的是:根据 GameNo 对它们进行分组,并为其提供另一列,其中包含根据 PlayerScore 排列的玩家位置。
tib <- tib %>% group_by(GameNo) %>% ...
最终结果应该是这样的:
PlayerName GameNo PlayerScore Placement
<chr> <dbl> <dbl> <dbl>
1 P1 1 10 2
2 P2 1 15 1
3 P3 1 9 3
4 P1 2 8 3
5 P2 2 12 2
6 P3 2 18 1
我们可以按 'GameNo' 分组并创建 'Placement' 作为 'PlayerScore'`
的 rank
library(dplyr)
tib <- tib %>%
group_by(GameNo) %>%
mutate(Placement = rank(-PlayerScore)) %>%
ungroup
-输出
tib
# A tibble: 6 x 4
PlayerName GameNo PlayerScore Placement
<chr> <dbl> <dbl> <dbl>
1 P1 1 10 2
2 P2 1 15 1
3 P3 1 9 3
4 P1 2 8 3
5 P2 2 12 2
6 P3 2 18 1
我有一个标题或数据框如下:
tib <- tibble(PlayerName=c("P1","P2","P3","P1","P2","P3"), GameNo=c(1,1,1,2,2,2), PlayerScore=c(10,15,9,8,12,18))
所以,我想做的是:根据 GameNo 对它们进行分组,并为其提供另一列,其中包含根据 PlayerScore 排列的玩家位置。
tib <- tib %>% group_by(GameNo) %>% ...
最终结果应该是这样的:
PlayerName GameNo PlayerScore Placement
<chr> <dbl> <dbl> <dbl>
1 P1 1 10 2
2 P2 1 15 1
3 P3 1 9 3
4 P1 2 8 3
5 P2 2 12 2
6 P3 2 18 1
我们可以按 'GameNo' 分组并创建 'Placement' 作为 'PlayerScore'`
的rank
library(dplyr)
tib <- tib %>%
group_by(GameNo) %>%
mutate(Placement = rank(-PlayerScore)) %>%
ungroup
-输出
tib
# A tibble: 6 x 4
PlayerName GameNo PlayerScore Placement
<chr> <dbl> <dbl> <dbl>
1 P1 1 10 2
2 P2 1 15 1
3 P3 1 9 3
4 P1 2 8 3
5 P2 2 12 2
6 P3 2 18 1