Announcement

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

  • Counting letters in Stata?

    Hello

    Maybe a weird question, but I can do

    Code:
    local i = 1
    foreach x of numlist 1/10 {
      di `i'
      local i = `i' + 1
    }
    to count from 1 to 10 with i -- is there a simple way to do the same thing for letters? I.e. a simple way to have a macro containing only a letter take on the next letter in the alphabet?

    Thanks
    Jo

  • #2
    Code:
    forvalues j = 1/10 {
    local letter = char(64+`j')
    display `"`letter'"'
    }
    will "count" from A to J. Evidently if you go beyond 26, you are out of the Roman alphabet. If you wanted lower case letters, replace 64 with 96 in the above.

    Or, perhaps more transparently:

    Code:
    forvalues j = 1/10 {
        local letter: word `j' of `c(ALPHA)'
        display `"`letter'"'
    }
    Last edited by Clyde Schechter; 19 Apr 2020, 14:42.

    Comment


    • #3
      I am not sure what you want to achieve but the alphabet is stored in the system scalars c(alpha) and c(ALPHA)
      Code:
      creturn list
      disp c(alpha)
      disp c(ALPHA)
      So you could modify your code to something like
      Code:
      forvalues i=1/10 {
      local letters `letters' `=word(c(alpha),`i')'
      }

      Comment


      • #4
        I'll add that an alternative to Clyde's code is
        Code:
        local nl 10
        local list = substr("`c(alpha)'",1,2*`nl')
        foreach letter of local list {
            display `"`letter'"'
        }
        which goes through the first nl letters of the alphabet.

        Comment


        • #5
          Code:
          tokenize "`c(alpha)'"
          forval j = 1/10 {
               di "``j''"
          }

          Comment


          • #6
            Thanks, this was great. To show what this is good for:

            Code:
            sysuse auto, clear
            tokenize "`c(ALPHA)'"
            
            local i 1
            foreach x of varlist rep78 headroom trunk weight {
             di `i' _skip(5) "`x'"
             twoway scatter mpg `x', title("``i''") name("`x'", replace)
             local ++i
            }
            graph combine rep78 headroom trunk weight

            Comment


            • #7
              As in another thread https://www.statalist.org/forums/for...eady-in-memory crossplot and combineplot (SSC) do precisely that for you.

              Comment

              Working...
              X