Announcement

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

  • Map Letters to positions in alphabet

    Hi. I'd like to generate a variable that contains the relative positions of letters (in another var) in the alphabet. For example:

    Code:
    var1    new_var
    A       1
    B       2
    C       3
    C       3
    X       24
    What's an elegant way to do this?

  • #2
    This works, although I'd like to think there's a better method:

    Code:
    clear
    input str1 var1    new_var
    A       1
    B       2
    C       3
    C       3
    X       24
    end
    
    di "`c(ALPHA)'"
    tokenize "`c(ALPHA)'"
    forval j = 1/26 {
         label def alphabet `j' "``j''", add
    }
    encode var1, gen(wanted) label(alphabet)
    assert wanted == new_var
    P.S. please close the first thread you started.
    Last edited by Nick Cox; 04 Nov 2015, 12:48.

    Comment


    • #3
      Thanks.

      How do I close a thread?

      Comment


      • #4
        You summarize from your point of view, especially saying what worked.

        The FAQ does have advice on this:

        16. Should I close threads I start?

        Closing a thread you started is important, especially by reporting what solved your problem. You can then thank those who tried to help.

        Comment


        • #5
          Nick,

          Do you know the history behind why there is a char() function in Stata (converting a number to an ASCII character), but there is no inverse ascii() function in Stata (converting a character to its ASCII collating sequence number), only in Mata?

          One could theoretically use the Mata ascii() function to solve Allen's problem, but the headache involved in moving the data in and out of Mata just for that purpose is probably not worth the trouble compared to your method.

          Regards,
          Joe

          Comment


          • #6
            I don't know of an specific explanation in this case.

            The pattern with functions and commands that are or should be paired is typically all too human.

            Say a developer really wants a function for some purposes and implements it, but overlooks or never gets round to implementing its inverse. We're all busy and easily distracted.

            I know this can happen to us all. I wrote destring first because I really wanted it (and then Bill Gould of StataCorp joined in and did it properly) and then wrote tostring as an exercise, not thinking that the latter was needed. But then reasons for tostring as well emerged quickly and it too was made public.

            Comment

            Working...
            X