Announcement

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

  • Variable order loop

    Hi all, I have a data set with 280 variables. All but ~35 of them are repeats of question of variables ordered by event. The event is numbered (event1, event2, event3 etc.) but the questions are not (for example event1QX, event1QY, ....event2QX,event2QY, etc.). I'd like to create a loop to reorder the variables first in order of the event (so all questions for event1 are first) and then in a specific order for the questions since the questions aren't actually numbered. So there will be two levels of ordering. I've tried creating a looping for this but the foreach command is looping over the sequence order so that I get event1QX event2QX.......event1QY event2QY and vice versa.

    ds event1QX-event25QZ
    local event "`rvarlist'"
    order `event', seq
    foreach var of local event {
    order event*QX event*QY event*QZ event*QA event*QB
    }

  • #2
    What about something like this...

    Code:
    clear
    set obs 1
    foreach l in X A Z B Y {
        foreach n in 3 6 2 1 4 5 {
            gen event`n'Q`l'=.
        }
    }
    drop event2QY
    
    
    foreach n in 6 5 4 3 2 1 {
        foreach l in B A Z Y X  {
            capture order event`n'Q`l'
        }
    }
    Because of the way -order- works, you can loop backwards through the event numbers and then backwards through the questions. The -capture- before -order- is necessary if there are some questions that weren't asked for some events.

    Lance

    Comment


    • #3
      I wouldn't order again and again. I would separate this into getting the variable names in the right order first and then issuing order just once.

      Sample code is therefore a twist on Lance's:



      Code:
      local neworder 
      
      forval j = 1/25 { 
          local neworder `neworder' event`j' event`j'QX event`j'QY event`j'QZ event `j'QA event`j'QB 
      }
      
      order `neworder'

      Comment


      • #4
        I couldn't get that code to work but I found it in another posting after a day of searching. See link below. Appreciate the help.

        *Nick I saw your post late, but that works too. Its a different take on using forval to specify the order which worked in both codes. Thanks!
        I'm using Stata 14 and have a seemingly simple question about order the variables in my list. I have multiple variables that are tagged with numbered stubs at
        Last edited by Jenn OKeeffe; 08 Jun 2018, 06:05. Reason: Update

        Comment

        Working...
        X