samedi 6 juin 2020

R - Getting values from other columns when conditions are met

I have a data table something like this.

Firm Year Moveyear Address OriginAddress DestinationAddress
  A  2000                     
  A  2001 2001              15Grand_Ave     700Grand_Ave
  A  2002
  A  2003 2003              700Grand_Ave    20Washington_Ave
  A  2004
  B  2000
  B  2001 
  B  2002 2002              2730State_st    40Washington_Ave
  B  2003
  B  2004
  C
  .
  .

It is a panel dataset showing relocation information of each firm for multiple years. I want to add (or assign) address information to 'Address' column by using 'OriginAddress' and 'DestinationAddress' columns.

For example, 15Grand_Ave should be assigned to Firm A's Address column in 2000 since it was the original address before the firm moves to 700Grand_Ave in 2001. And 700Grand_Ave should be assigned to Firm A's Address column in 2001 and 2002 since it was its address before it moves to 20Washington_Ave in 2003.

So the result that I want :

Firm Year Moveyear  Address        OriginAddress DestinationAddress
  A  2000         15Grand_Ave            
  A  2001 2001    700Grand_Ave      15Grand_Ave     700Grand_Ave
  A  2002         700Grand_Ave
  A  2003 2003    20Washington_Ave  700Grand_Ave    20Washington_Ave
  A  2004         20Washington_Ave
  B  2000         2730State_st
  B  2001         2730State_st
  B  2002 2002    40Washington_Ave  2730State_st    40Washington_Ave
  B  2003         40Washington_Ave
  B  2004         40Washington_Ave
  C
  .
  .

I am guessing I need to use for-loop and ifelse statement in R but I am having trouble with coding. Please share any ideas with me.

Aucun commentaire:

Enregistrer un commentaire