Announcement

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

  • reversing the value of variables

    I have 11 variables named num_pih1 to num_pih11 scored 0 to 8.
    I need to reverse the values of variables so that the one scored 0 in original variable becomes 8 in new variable.

    Code:
    gen pih1=.
    replace pih1=0 if num_pih1==8
    replace pih1=1 if num_pih1==7
    replace pih1=2 if num_pih1==6
    replace pih1=3 if num_pih1==5
    replace pih1=4 if num_pih1==4
    replace pih1=5 if num_pih1==3
    replace pih1=6 if num_pih1==2
    replace pih1=7 if num_pih1==1
    replace pih1=8 if num_pih1==0
    I tried this code, it works but I was wondering if there is a shorter way to do it for all 11 variables.
    Thanks

  • #2
    See: help recode

    The following creates new variables new_num_pih1, new_num_pih2... containing the recodes

    Code:
    recode num_pih* (0=8) (1=7) (2=6) (3=5) (4=4) (5=3) (6=2) (7=1) (8=0), prefix(new_)
    You can rename the variable to pih1, pih2, etcc with rename (see: help rename group )
    Code:
    rename new_num_* *
    Stata/MP 14.1 (64-bit x86-64)
    Revision 19 May 2016
    Win 8.1

    Comment


    • #3
      Code:
      foreach var of varlist list out your eleven variables here{
             recode `var' (8=0) (7=1) (6=2) (5=3) (3=5) (2=6) (1=7) (0=8)
      }
      Should do the trick

      Comment


      • #4
        Perfect, Thank you Carole

        Comment


        • #5
          Code:
          forval i=1/11 {
          gen pih`i' = 8 - num_pih`i'
          }

          Comment


          • #6
            Thanks Chris and Romalpa, great to know there are many ways to do this.

            Comment

            Working...
            X