Announcement

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

  • Loop for variable creation

    Hi,
    Following is snapshot of the data

    Below is the dataex of what I currently have

    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input str7 poc float date_stata long(tp1 tp2 tp3) float count
    "MTU" 22479 50 25  5 1
    "MTU" 22479 50 25  5 2
    "MTU" 22479 50 25  5 3
    "MTU" 22480 60 30 10 1
    "MTU" 22480 60 30 10 2
    "MTU" 22480 60 30 10 3
    "MTU" 22481 70 40 15 1
    "MTU" 22481 70 40 15 2
    "MTU" 22481 70 40 15 3
    end
    format %tdMonth_DD,_CCYY date_stata

    Now, I want to create a new variable i.e., "new_var" that will have the value of tp1 if count == 1, value of tp2 if count ==2 and so on..

    Currently I am showing the data for upto 3 observations for each day, in the real data, the each day has minimum observations of 50 and max observations of 1500, so it is very difficult to write a manual code e.g.,

    g new_var = .
    replace new_var = tp1 if count == 1
    replace new_var = tp2 if count == 2



    Any suggestion loop ?

    Below is the dataex of what I want. "new_var" is the new variable that I want to generate.

    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input str7 poc float date_stata long(tp1 tp2 tp3) float(count new_var)
    "MTU" 22479 50 25  5 1 50
    "MTU" 22479 50 25  5 2 25
    "MTU" 22479 50 25  5 3  5
    "MTU" 22480 60 30 10 1 60
    "MTU" 22480 60 30 10 2 30
    "MTU" 22480 60 30 10 3 10
    "MTU" 22481 70 40 15 1 70
    "MTU" 22481 70 40 15 2 40
    "MTU" 22481 70 40 15 3 15
    end
    format %tdMonth_DD,_CCYY date_stata

    Thanks

  • #2
    Based on the dataex it seems that tp can range from tp1 to tp1500 and count can vary from 1 to 1500 as well. The following loop will work in case my understanding is correct

    Code:
    gen new_var = .
    
    forvalues i = 1/1500{
    replace new_var = tp`i' if count == `i'
    }

    Comment


    • #3
      Thanks Tarun, it worked like a charm.

      Comment

      Working...
      X