Announcement

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

  • for loop

    Hi there,

    I have the following code in stata:

    *2018
    *Form 4
    generate Form4= 1 if Performance2018 ==1 & form== "4"
    replace Form4= 0 if Performance2018==0 & form=="4"
    replace Form4= 3 if Performance2018==3 & form=="4"
    replace Form4= 5 if Performance2018==5 & form=="4"
    label values Form4 Einteilung

    *Distinct
    egen tag2018 = tag(Form4 cik)
    generate distinctform2018= 1 if tag2018 ==1 & Form4 == 1 & year ==2018
    replace distinctform2018 = 3 if tag2018 ==1 & Form4 == 3 & year ==2018
    replace distinctform2018 = 0 if tag2018 ==1 & Form4 == 0 & year ==2018
    replace distinctform2018 = 5 if tag2018 ==1 & Form4 == 5 & year ==2018
    label values distinctform2018 Einteilung
    drop tag2018

    *Average
    egen tag2018 = tag(distinctform2018 Form4)
    bysort cik Form4: gen Form4forms2018 = _N
    generate Form4_gute2018= Form4forms2018 if Form4 ==1 & distinctform2018 == 1
    generate Form4_schlechte2018= Form4forms2018 if Form4 ==0 & distinctform2018 == 0

    drop Form4 distinctform2018 tag2018 Form4forms2018


    My concern is to repeat this Code for every year till 2009. Is it possible with a for loop code that only the year (2018, 2017,2016,2015...) will change? Otherwise i have copy and paste the whole code and change the year manually.

    Thank you a lot in advance!

    Cheers,

    Sergej

  • #2
    Welcome to Statalist.

    The forvalues command seems to be what you need to create your loop. I think this (untested) code will at least start you on your way.
    Code:
    forvalues y = 2009/2018 {
    
    *Form 4
    generate Form4= 1 if Performance`y' ==1 & form== "4"
    replace Form4= 0 if Performance`y'==0 & form=="4"
    replace Form4= 3 if Performance`y'==3 & form=="4"
    replace Form4= 5 if Performance`y'==5 & form=="4"
    label values Form4 Einteilung
    
    *Distinct
    egen tag`y' = tag(Form4 cik)
    generate distinctform`y'= 1 if tag`y' ==1 & Form4 == 1 & year ==`y'
    replace distinctform`y' = 3 if tag`y' ==1 & Form4 == 3 & year ==`y'
    replace distinctform`y' = 0 if tag`y' ==1 & Form4 == 0 & year ==`y'
    replace distinctform`y' = 5 if tag`y' ==1 & Form4 == 5 & year ==`y'
    label values distinctform`y' Einteilung
    drop tag`y'
    
    *Average
    egen tag`y' = tag(distinctform`y' Form4)
    bysort cik Form4: gen Form4forms`y' = _N
    generate Form4_gute`y'= Form4forms`y' if Form4 ==1 & distinctform`y' == 1
    generate Form4_schlechte`y'= Form4forms`y' if Form4 ==0 & distinctform`y' == 0
    
    drop Form4 distinctform`y' tag`y' Form4forms`y'
    
    }

    Comment

    Working...
    X