mardi 6 avril 2021

Ifelse with multiple conditions across many rows/

Looking to add a column based on the values of other columns, but over more than one row.

DF:
Studios: A, B, C ...
Year:2000-2020
Id:r1,r2,r3,r4...
Top1:0,1,0,0,0

Starting data set looks like this :

id Year Studio Top1
r1 2020 A 0
r2 2001 B 0
r3 2019 A 1
r45 2005 D 1
r34 2005 E 1

Ifelse Statemets (probably): What I am trying to achieve is "create column PreviousTop1.If column Studio1=studioX where year=year-1 and Top1=1. *For clarification: studio1 is referring to the studio1 my id is currently at. While studioX is the same studio as studio1 in different id.

Desired Output:

id Year Studio Top1 PreviousTop1
r1 2020 A 0 1
r2 2001 B 0 0
r3 2019 A 1 0
r45 2005 D 1 0
r34 2005 E 1 0

Reasoning for proper Answer PreviousTop=1,in row 1 because r3 exists. So I need to check the whole column for 1 instance that conditions are true and then break.

Aucun commentaire:

Enregistrer un commentaire