MichaelD
MichaelD

Reputation: 51

Creation of new row dependent on date in another column

Im struggling with a wrangling task at the moment and any help would be appreciated.

See DF

Var 1 Date
P1 13/09/2020
P2 13/09/2020
P3 20/09/2020
P4 20/09/2020
P5 27/09/2020
P6 27/09/2020

Date is in %d/%m/%Y format and is currently ordered descending with the earliest date first. My intent is to have the earliest date as Gameweek 1 and when the date changes, the row input is Gameweek 2. See my intended DF:

Var 1 Date Gameweek
P1 13/09/2020 Gameweek 1
P2 13/09/2020 Gameweek 1
P3 20/09/2020 Gameweek 2
P4 20/09/2020 Gameweek 2
P5 27/09/2020 Gameweek 3
P6 27/09/2020 Gameweek 3

Again, any help is appreciated.

Thanks

Upvotes: 0

Views: 25

Answers (2)

TarJae
TarJae

Reputation: 78917

library(dplyr)

df %>%
group_by(Date) %>%
mutate(Gameweek = paste("Gameweek", rownumber(), sep=" "))

Upvotes: 1

norie
norie

Reputation: 9857

You could use factor.

df$Gameweek <-factor(df$Date, labels='Gameweek')

Sample Output

  Var1       Date  Gameweek
1   P1 13/09/2020 Gameweek1
2   P2 13/09/2020 Gameweek1
3   P3 20/09/2020 Gameweek2
4   P4 20/09/2020 Gameweek2
5   P5 27/09/2020 Gameweek3
6   P6 27/09/2020 Gameweek3

Upvotes: 1

Related Questions