Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Generate a lead variable in a panel

    Cross-posted on stack overflow.


    I need help in generating a lead variable in a panel. I want to generate a lead income variable (let's call it V1) by CMA, Province and Year such that the data looks like;

    CMA Province Year Income V1
    TO A 1990 $5 $8
    TO A 1991 $8 .
    MT A 1990 $12 $7
    MT A 1991 $7 .
    AB B 1990 $5 $15
    AB B 1990 $15 .
    etc

    I was using the following codes, but I was getting only missing values.

    gsort CMA Province -Year Income
    gen ld_inc = Income[_n-1] if Year == Year[_n-1] + 1
    replace ld_inc = ld_inc[_n-1] if Year == Year[_n-1] & missing(ld_inc)

    Is there something wrong with my code and what I am getting wrong? Thanks in advance.
    Last edited by Musah Khalid; 12 Mar 2019, 14:05.

  • #2
    Review the FAQs on the top left-hand side of the page for guidance on how to present example data using the dataex command. Stata has time-series operators that are suited for this purpose.

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str3(CMA Province) float(Year Income V1)
    "TO" "A" 1990  5  8
    "TO" "A" 1991  8  .
    "MT" "A" 1990 12  7
    "MT" "A" 1991  7  .
    "AB" "B" 1990  5 15
    "AB" "B" 1991 15  .
    end
    
    egen id= group(CMA Province), label
    xtset id Year
    gen wanted = F.Income
    assert wanted==V1

    Comment

    Working...
    X