mercredi 25 novembre 2020

R - Create a column with consecutive numbers and reset based on other column using mutate

I am trying to use mutate to create a new variable game_plus in my df, which counts the number of days since an event occurred in another column game and resets every time the event occurs. For instance, the variable game in my df is binary and can take on either "Game" or "Training". I was thinking to use a nested ifelse statement to generate the following output:

game         game_plus
Game             0
Training         1
Training         2
Training         3
Game             0
Training         1
Training         2
Game             0
Training         1
Training         2
Training         3
Training         4

I would also like to the opposite for a column game_minus, which essentially counts the number of days before an event, like the following.

game         game_plus      game_minus
Game             0              0
Training         1              3
Training         2              2
Training         3              1
Game             0              0
Training         1              2
Training         2              1 
Game             0              0
Training         1              4
Training         2              3
Training         3              2
Training         4              1

Can anybody assist with this? I know I can use ifelse(game == "Game", 0, but I am struggling to figure out how to incorporate the - prior to or since the event occurred- element into this ifelse statement. Any help would be appreciated!

Aucun commentaire:

Enregistrer un commentaire