1

I have a tibble or data frame as follows:

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))

So, what I want to do is: group them according to the GameNo, and give it another column which will contain the Players' placement according to their PlayerScore.

tib <- tib %>% group_by(GameNo) %>% ...

The end result should look like this:

  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
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • Does this answer your question? [R - Group by variable and then assign a unique ID](https://stackoverflow.com/questions/39650511/r-group-by-variable-and-then-assign-a-unique-id) – user438383 Jun 07 '21 at 18:55
  • @user438383 that post is about replacing groups with a unique ID, whereas this one is about calculating the rank within a group. Probably been answered before, just not in that question – camille Jun 08 '21 at 03:02

1 Answers1

0

We can do a group by 'GameNo' and create the 'Placement' as the rank of 'PlayerScore'`

library(dplyr) 
tib <- tib %>%
      group_by(GameNo) %>% 
      mutate(Placement = rank(-PlayerScore)) %>%
      ungroup

-output

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
akrun
  • 874,273
  • 37
  • 540
  • 662