Announcement

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

  • Renaming multiple variables in a loop

    Hi,

    How can I rename multiple variables without having to manually rename every single one of them using a loop? I am using the following formula but I get an error:

    . local a " qq01 qq02 qq03 qq04 qq05 qq06 qq07 qq08a qq08b qq09a qq09b"

    . local b "qq_old01 qq_old02 qq_old03 qq_old04 qq_old05 qq_old06 qq_old07 qq_old08a qq_old8b qq_old9a qq_old9b"

    . foreach x of varlist `a' {
    2. rename `x' `b'
    3. }

    syntax error
    Syntax is
    rename oldname newname [, renumber[(#)] addnumber[(#)] sort ...]
    rename (oldnames) (newnames) [, renumber[(#)] addnumber[(#)] sort ...]
    rename oldnames , {upper|lower|proper}


    Best,
    Shehryar
    A new STATA user

  • #2
    Local macro b within the loop is exactly what it is outside the loop, a list with several names. The loop can't read your intent, which is to select a name each time round the loop. You could do this

    .
    Code:
    local a  qq01 qq02 qq03 qq04 qq05 qq06 qq07 qq08a qq08b qq09a qq09b
    
    local b qq_old01 qq_old02 qq_old03 qq_old04 qq_old05 qq_old06 qq_old07 qq_old08a qq_old8b qq_old9a qq_old9b
    
    foreach x of varlist `a' {
           gettoken new b : b
           rename `x' `new'
    }
    but why do that when you can do this

    Code:
    rename (qq01 qq02 qq03 qq04 qq05 qq06 qq07 qq08a qq08b qq09a qq09b) (qq_old01 qq_old02 qq_old03 qq_old04 qq_old05 qq_old06 qq_old07 qq_old08a qq_old8b qq_old9a qq_old9b)

    Comment


    • #3
      Depending on the other variable names in the dataset, this might be as short as

      Code:
      rename (qq*) (qq_old*)
      Best
      Daniel

      Comment


      • #4
        Building on Daniel's answer, if there are other variables beginning qq that are not to be renamed, if those are not qq followed by two digits, then
        Code:
        rename (qq(##)*) (qq_old(##)*)
        will only rename variables beginning with qq and two digits.
        Code:
        . ds
        qq01   qq99a  qqfoo
        
        . rename (qq(##)*) (qq_old(##)*)
        
        . ds
        qq_old01   qq_old99a  qqfoo
        This technique, and Daniel's, and many other powerful variants, are described in the output of the help rename group command.

        Comment


        • #5
          Thank you so much guys,it works now!

          Best,
          Shehryar

          Comment

          Working...
          X