Announcement

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

  • Looping over a (non-continuous) list on descending order

    Hi,

    I have the variables: xyz1983 xyz1984 xyz1986 ...xyz2016 (not all years, some are missing)
    now I need to create a loop that loops over the years in my list starting from 2016 to the earliest.
    I manage to save the years from the variable name in a local list, but only in ascending order, how can I reverse the order or solve this otherwise?

    [qui d xyz*, varlist

    local wlist = r(varlist)
    local wlist: subinstr local wlist "xyz" "", all

    ]
    Last edited by Da GXHI; 20 Jan 2023, 03:23.

  • #2


    Code:
    clear 
    set obs 1 
    foreach v in xyz1983 xyz1984 xyz1986 xyz2016 { 
        gen `v' = 1 
    }
    
    * you start here 
    unab vars : xyz* 
    local years : subinstr local vars "xyz" "", all 
    local nyears : word count `years'
    
    tokenize "`years'"
    forval i = `nyears'(-1)1 {
        local newlist `newlist' ``i''
    }
    
    * result in our case 
    di "`newlist'"
    
    2016 1986 1984 1983

    Comment


    • #3
      This works too:

      Code:
      clear 
      set obs 1 
      foreach v in xyz1983 xyz1984 xyz1986 xyz2016 { 
          gen `v' = 1 
      }
      
      * you start here 
      unab vars : xyz* 
      local years : subinstr local vars "xyz" "", all 
      
      mata 
      wanted = tokens("`years'")
      wanted = wanted[cols(wanted)::1]
      st_local("wanted", invtokens(wanted))
      end 
      
      di "`wanted'"

      Comment


      • #4
        great. thanks a lot!

        Comment


        • #5
          It would be probably easier if you use -while- for the descending loop, and just make your code to not break when the year is missing, basically some variation of Method 3 in this FAQ https://www.stata.com/support/faqs/d...-with-foreach/

          And he descending loop would be something like this:

          Code:
          . local i = 2016
          
          . while `i'>=2000 {
            2. dis `i'
            3. local i = `i' - 1
            4. }
          2016
          2015
          2014
          2013
          2012
          2011
          2010
          2009
          2008
          2007
          2006
          2005
          2004
          2003
          2002
          2001
          2000

          Comment

          Working...
          X