Announcement

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

  • How to write more efficient loops (forvalues)

    Dear statalist users,

    I'm wondering if it's possible to write a more efficient iterator in these three cases.


    case 1.

    gen making = 20190 if month==1 & year == 2019

    forvalues i=2/9 {
    replace making = 20190 if month==`i' & year==2019
    }

    forvalues i=1/9 {
    replace making = 20200 if month==`i' & year==2020
    }

    forvalues i=1/9 {
    replace making = 20210 if month==`i' & year==2021
    }

    forvalues i=1/6 {
    replace making = 20220 if month==`i' & year==2022
    }

    forvalues i=10/12 {
    replace making = year if month==`i'
    }


    case 2.
    gen year_month = making*10 + month if month== 1 & year == 2019

    forvalues i=2/9 {
    replace year_month = making*10 + month if month==`i' & year==2019
    }

    forvalues i=1/9 {
    replace year_month = making*10 + month if month==`i' & year==2020
    }

    forvalues i=1/9 {
    replace year_month = making*10 + month if month==`i' & year==2021
    }

    forvalues i=1/6 {
    replace year_month = making*10 + month if month==`i' & year==2022
    }

    forvalues i=10/12 {
    replace year_month = making*100 + month if month==`i'
    }


    case 3.

    gen quarter = 1 if month == 1 |month == 2| month == 3
    replacequarter = 2 if month == 4 |month == 5| month == 6
    replacequarter = 3 if month == 7 |month == 8| month == 9
    replacequarter = 4 if month == 10|month == 11| month == 12



    thank you!

  • #2
    None of these cases requires any loop at all.

    Case 1 can be done in a few lines of code:
    Code:
    gen making = 10*year
    replace making = 10*year if year == 2022 & inrange(month, 1, 6)
    replace making = year if inrange(month, 10, 12)
    (In fact, these three lines of code can be reduced to a single line of code, but it would be rather opaque, so better to do it in three easy-to-understand lines of code.)

    Case 2 is rather similar
    Code:
    gen year_month= 10*making+month if inrange(year, 2019, 2021) & inrange(month, 1, 9)
    replace year_month = 10*making_month if year == 2022 & inrange(month, 1, 6)
    replace year_month = making*100+month if inrange(month, 10, 12)
    Case 3 is a one-liner
    Code:
    gen quarter = ceil(month/3)

    Comment

    Working...
    X