Announcement

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

  • Calling multiple elements in the foreach macro

    Hello all,

    I am stuck on how to code a loop that will essentially execute the following for the multiple time periods:

    corr x y if year>=1983 & year<1990
    corr x y if year>=1990 & year<2000
    corr x y if year>=2000 & year<2012

    Since I'm producing more than just simple correlations, including different scenarios each time period and graphs with the time period coded in the title, the code is quite lengthy. Ideally, I'd run a loop that looks something like that below, but am not sure how to call a second set of values for the end of the time period

    foreach y in 1980 1992 2000 2011 {
    corr x y if year>=`y' & year < [???]
    }

    I've searched online and on Statalist, but seems to be a complicated search and not yielding any results. Any pointers is much appreciated!

    Nabeela

  • #2
    Code:
    local years 1980 1992 2000 2011 . // DON'T FORGET THE . AT THE END
    local n_years: word count `years'
    forvalues i = 1/`=`n_years'-1' {
        local ybegin: word `i' of `years'
        local yend: word `=`i'+1' of `years'
        corr xy if year >= `ybegin' & year < `yend'
    }
    Note: No example data provided, so not tested. Beware of typos or other errors.

    Comment


    • #3
      This worked beautifully - THANK YOU!

      Comment


      • #4
        Although extending technique is always interesting, I would just write here

        Code:
        corr x y if inrange(year, 1983, 1989)
        
        corr x y if inrange(year, 1990, 1999) 
        
        corr x y if inrange(year. 2000, 2011) 
        which is shorter and (I suggest) not more difficult to understand.

        Comment

        Working...
        X