Announcement

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

  • Rename all variables

    Hi,

    I want to rename all the variables of my data set erasing the last 2 digits of each variable name. I saw a post from Nick Cox answering this question but his code does not seem to work for me.

    The code I am running is:

    foreach var of varlist * {
    local newname = substr(`var', 1, length(`var')-2)
    rename `var' `newname'
    }

    When I run it Stata says "type mismatch". Do you know what seems to be the problem?
    Last edited by Santiago Deregil; 28 Sep 2017, 16:35.

  • #2
    I have to suggest that "a post by Nick Cox" is a little vague as a reference as there are perhaps 50,000 of them.

    Be that as it may, I would not have written that if I was thinking.

    Code:
    local newname = substr("`var'", 1, length("`var'")-2)
    If you can give the URL for any post suggesting that I shall be suitably embarrassed. You need to insist that the variable name is a literal string.

    Whether the code is the right solution for you can't be guessed except to underline that it removes the last two characters of each variable name.

    Comment


    • #3
      Thank you! It worked. About your post, I think it was my mistake and mised the " " to insist it is a string. Here is the URL: https://www.stata.com/statalist/arch.../msg00957.html

      Thank you again.

      Comment


      • #4
        As Nick points out, the last two characters might not be numbers. I think

        Code:
        rename (*(##)) (*)
        would be a more explicit solution.

        Best
        Daniel

        Comment


        • #5
          I didn't say that either.

          Let's back up.

          1. In 2005 I posted an answer to a different question.

          2. Santiago started with that code and changed it towards his problem. His code was buggy because he left out quotation marks.

          3. The fixed code drops the last two characters from each name. Whether the characters are numeric or not doesn't signify in the code in #1 corrected in #2.

          4. However, if the characters are numeric, then Daniel's solution is better. No loop, explicit structure change.

          Comment


          • #6
            How do i rename all my variables in a dataset to begin with q_ . I am using Stata 18 MP

            Comment


            • #7
              see "rule" 11 in
              Code:
              help rename group

              Comment

              Working...
              X