Announcement

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

  • Increment a letter

    I'm trying to do the following, but obviously incrementing the letter the way I have does not work. Any ideas?

    HTML Code:
    local letter = "D"
        forvalue i = 1(1)5 {
            preserve
                // Keep data from the most recent year
                keep if juris == `i'
                keep nos file_$y1   
                
                collapse (sum) file_*, by(nos)
                
                sort nos 
                
                // Reapply pre-collapse labels
                foreach v of var * {
                    label var `v' "`l`v''"
                }
                
                export excel using "$output\Judicial_Business_Tables.xlsx", sheet("Fi_by_Juris_NOS") firstrow(varlabels) sheetmodify cell(`letter'2)
                
                local letter = `letter' + 1
            restore
        }

  • #2
    A framework is this


    Code:
    tokenize "D E F G H"
    forval i = 1/5 { 
         .... 
    }
    Within the loop references to `i' will be evaluated as references to 1 2 3 4 5 in turn and references to ``i'' will be evaluated as references to D E F G H in turn.

    Comment


    • #3
      Nick's approach is more elegant than mine, but here's another common way to work through a list parallel to a numlist. (I'm still afraid of the positional local macros `1', `2', etc. <grin>)
      Code:
      local letters = "D E F G H"
      forval i = 1/5 {
        // next item in the blank-delimited list of items
        local letter = word("`letters'", `i')
        preserve
         ...
         ...
        export excel...
        restore
      }

      Comment


      • #4
        A somewhat more fancy version uses Mata to generate the letters during the iteration
        Code:
        forval i=1/5{
                 mata: st_local("letter", numtobase26(`=`i'+3')) // convert the number into an upper case letter and put it in the local macro "letter"
                 .... 
        
        }

        Comment


        • #5
          crossed with #4 above:

          In addition, the following variants may be used:
          Code:
          forvalues i = 4/8 {
             
              local col = word( "`c(ALPHA)'" , `i' )
             
              display "`col'"
          }
          
          * mata function numtobase26() 
          
          forvalues i = 4/8 {
             
              mata : st_local( "col", numtobase26(`i') )
             
              display "`col'"
          }
          
          * for i > 26
          
          foreach i of numlist 1/2 27/28 53/54 {
             
              mata : st_local( "col", numtobase26(`i') )
             
              display "`col'"
          }
          Last edited by Bjarte Aagnes; 16 Jul 2020, 13:32.

          Comment

          Working...
          X