Announcement

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

  • Replacing observations with conditions using loop

    Hi, I need some help

    I'm working with migration data and I'd like to replace the values of the variable p10 by adding "01" to the observation by using a loop.

    This is what I want to do:

    replace p10 = 101 if p10==1
    replace p10 = 201 if p10==2
    replace p10 = 301 if p10==3
    replace p10 = 401 if p10==4
    replace p10 = 501 if p10==5
    replace p10 = 601 if p10==6
    replace p10 = 701 if p10==7
    replace p10 = 801 if p10==8
    replace p10 = 901 if p10==9
    replace p10 = 1001 if p10==10

    This is the loop that is not working

    forvalues i = 1/10 {
    replace p10 = `i'01 if p10 = `i'
    }


  • #2
    I don't see any reason for a loop here; why not just:
    Code:
    replace p10=(p10*100)+1

    Comment


    • #3
      Rich demonstrates good technique in post #2 - an ounce of analysis is worth a pound of loops, as the old programming adage goes.

      The problem in the code in post #1 that led to it not working is that
      Code:
      replace p10 = `i'01 if p10 = `i'
      should read
      Code:
      replace p10 = `i'01 if p10 == `i'
      because a double equal sign is used to denote comparison, while a single equal sign is used to denote assignment of a value to a variable.

      Comment


      • #4
        Thanks for your prompt reply, you are right. It works

        Comment

        Working...
        X