Announcement

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

  • How to replace values of a variabel based on certain conditions?

    Hi,

    pfa the example data:

    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input float(id round pcd open_during) str1 firm
    1 1 2 0 "a"
    1 2 2 0 "a"
    1 3 3 0 "a"
    1 4 4 1 "a"
    1 5 4 1 "a"
    2 1 3 0 "b"
    2 2 3 0 "b"
    2 4 4 1 "b"
    2 5 5 1 "b"
    3 1 1 0 "c"
    3 2 2 0 "c"
    3 3 2 0 "c"
    3 5 2 0 "c"
    4 1 1 0 "d"
    4 2 1 0 "d"
    4 5 1 0 "d"
    end


    the data here shows postcodes(pcd) for each individual (id) in each round (round) and whether it opened during our period of study (open_during=1), and the firm they are employed in (firm). For each individual, I want to replace a postcode with the one they had before the postcode was opened, if their firm of employment has remained unchanged.

    So my final data should look like following:

    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input float(id round pcd open_during) str1 firm
    1 1 2 0 "a"
    1 2 2 0 "a"
    1 3 3 0 "a"
    1 4 3 1 "a"
    1 5 3 1 "a"
    2 1 3 0 "b"
    2 2 3 0 "b"
    2 4 3 1 "b"
    2 5 3 1 "b"
    3 1 1 0 "c"
    3 2 2 0 "c"
    3 3 2 0 "c"
    3 5 2 0 "c"
    4 1 1 0 "d"
    4 2 1 0 "d"
    4 5 1 0 "d"
    end
    I'm struggling with coding this and would appreciate any help.
    Thanks!


  • #2
    This will do what you want with your example data:

    Code:
    bys id (round): replace pcd= pcd[_n-1] if firm==firm[_n-1] & open
    But I wonder what happens if someone changes firm after a new postcode is open?

    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input float(id round pcd open_during) str1 firm
    1 1 2 0 "a"
    1 2 2 0 "a"
    1 3 3 0 "a"
    1 4 3 1 "a"
    1 5 3 1 "b"
    end
    Do you keep the new postcode then for that last observation (highlighted)?

    Comment

    Working...
    X