user33125
user33125

Reputation: 197

panel data: give value of the last year to all the observations of the other years

If for one farmer, variable Z == 0, then I want to change the variable region for all observations of that farmer into the value of the last year of region for that farmer.

For instance:

farmID   - year     - region    - Z
1        - 2004     - BE100     - 0
1        - 2005     - BE100     - 0
1        - 2006     - BE112     - 0

Should become

farmID   - year     - region    - Z
1        - 2004     - BE112     - 0
1        - 2005     - BE112     - 0
1        - 2006     - BE112     - 0

I tried:

by farmID, if Z==0: replace region[n] = region[_N]

But that doesn't work. Any suggestions?

Upvotes: 0

Views: 915

Answers (1)

ℕʘʘḆḽḘ
ℕʘʘḆḽḘ

Reputation: 19405

bysort farmID (year) : gen last_region = region[_N]
#assuming Z does not vary within farmers
replace region = last_region if Z == 0

Upvotes: 1

Related Questions