mercredi 3 mars 2021

How can I do a conditional variable based on a ID and Year? R

I am working with a dataset of firms and try to know when they closed or not

So my dataset is like this:

Year    ID      Open
2014    a1       Y
2015    a1       Y
2016    a1       Y
2017    a1       Y

2014    a2       Y
2015    a2       N
2016    a2       N
2017    a2       N

2014    a3       Y
2015    a3       N
2016    a3       Y
2017    a3       N

And I want to make 3 conditional variables

If it´s opened in 2014 and closed in 2015 its 1, other way 0 If it´s opened in 2014 and closed in 2016 its 1, other way 0 If it´s opened in 2014 and closed in 2017 its 1, other way 0

So my desired dataset is this:

Year    ID      Open   C15   C16  C17
2014    a1       Y      -     -    -
2015    a1       Y      0     0    0
2016    a1       Y      0     0    0
2017    a1       Y      0     0    0  #Because firm never closed

2014    a2       Y      -     -    -
2015    a2       N      1     0    0 #Firm def. closed in 2015
2016    a2       N      0     1    0 #Still closed
2017    a2       N      0     0    1 #Still closed

2014    a3       Y      -     -    -
2015    a3       N      1     0    0  #Firm closed this year 
2016    a3       Y      0     0    0  #Firm is open again
2017    a3       N      0     0    1  #Firm closed again 

The data frame is grouped by ID, but I don´t know how to make the conditional on 2014

Aucun commentaire:

Enregistrer un commentaire