Home > Back-end >  Get season number for each player in DF
Get season number for each player in DF

Time:06-15

I have a df with the following columns: Name, Season Year, Yds.

I am trying to create a 4th column that says the number of the season for each player.

ex - L.Bell , 2012, 343

L.Bell , 2013, 367

B.Hall, 2022, 0

I would want row 1 col 4 to say 1, and row 2 col 4 to say 2, and now row 3 col 4 to say 1 again since it is for a new player.

Thanks

CodePudding user response:

Using tidyverse:

library(tidyverse)
df %>% group_by(Name) %>% mutate(Season = rank(Year))

Edit: Using base-R one can instead do:

df$season <- NA
split(df$season, df$Name) <- lapply(split(df$year, df$Name), rank)

CodePudding user response:

You can use order in ave to get the number of seasons.

x$Season <- ave(x$SeasonYear, x$Name, FUN=order)
x
#    Name SeasonYear Yds Season
#1 L.Bell       2012 343      1
#2 L.Bell       2013 367      2
#3 B.Hall       2022   0      1

Data:

x <- data.frame(Name = c("L.Bell", "L.Bell", "B.Hall")
              , SeasonYear = c(2012, 2013, 2022)
              , Yds = c(343, 367, 0) )
  •  Tags:  
  • r
  • Related