Niek Bezuijen Niek Bezuijen - 19 days ago 6
R Question

How to give every year a number for unique players

Is there a option to give every year a number for unique player in R?
example:

playerID yearID stint teamID lgID POS G PO A E DP score
<chr> <chr> <chr> <fctr> <fctr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 aardsda01 2004 1 SFN NL P 11 0 0 0 0 0.0
2 aardsda01 2006 1 CHN NL P 45 1 5 0 1 7.5
3 aardsda01 2007 1 CHA AL P 25 2 4 1 0 3.5
4 aardsda01 2008 1 BOS AL P 47 3 6 0 0 9.0
5 aardsda01 2009 1 SEA AL P 73 2 5 0 1 7.5
6 aardsda01 2010 1 SEA AL P 53 2 3 1 0 2.0
7 aardsda01 2012 1 NYA AL P 1 0 0 0 0 0.0
8 aardsda01 2013 1 NYN NL P 43 1 5 0 0 7.5
9 aardsda01 2015 1 ATL NL P 33 0 1 1 0 -1.0
10 aaronha01 1954 1 ML1 NL LF 105 205 4 6 0 -9.0



playerID yearID stint teamID lgID POS G PO A E DP score value
<chr> <chr> <chr> <fctr> <fctr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <chr>
1 aardsda01 2004 1 SFN NL P 11 0 0 0 0 0.0 1
2 aardsda01 2006 1 CHN NL P 45 1 5 0 1 7.5 2
3 aardsda01 2007 1 CHA AL P 25 2 4 1 0 3.5 3
4 aardsda01 2008 1 BOS AL P 47 3 6 0 0 9.0 4
5 aardsda01 2009 1 SEA AL P 73 2 5 0 1 7.5 5
6 aardsda01 2010 1 SEA AL P 53 2 3 1 0 2.0 6
7 aardsda01 2012 1 NYA AL P 1 0 0 0 0 0.0 7
8 aardsda01 2013 1 NYN NL P 43 1 5 0 0 7.5 8
9 aardsda01 2015 1 ATL NL P 33 0 1 1 0 -1.0 9
10 aaronha01 1954 1 ML1 NL LF 105 205 4 6 0 -9.0 1


The
value
Column is what I want.
Is there a option in R to do this???

Thanks,

Niek

Answer

Using dplyr you can:

df %>% group_by(playerID) %>% mutate(value=1:n()) %>% ungroup

This little pipe :

  1. groups your data.frame (let's say it's named df) based on playerID
  2. then creates an additional column (here named value but you can change this) filled with integers (a much needed as they are rows in every group)
  3. ungroups your data.frame once this is done.

Is that what you're looking for?

Comments