Announcement

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

  • Flag Changes in a Group with Some Missing Observations

    Dear all,

    This is my first time using statalist so any help would be much appreciated. I have a dataset where the id variable should uniquely identify individuals however there are some errors where this is not the case. There are some instances where 2 people of 2 different genders have the same id so I'd like to create a different id for these individuals.

    I have sorted my data by group and date and would like to create the flag_change variable in the example below, where a value of 1 is given if there is a change in the gender within a group, while taking into account the fact that there are some missing observations. I have tried the following code but this didn't work and just created missing values for the flag_change variable.

    bysort id: gen flag_change = (gender != gender[_n-1]) if _n > 1 & !missing(gender) & !missing(gender[_n-1])
    id gender date flag_change
    1 . 22 May 0
    1 Man 23 May 0
    1 Woman 15 Sep 1
    1 . 16 Sep 0
    2 Man 1 Dec 0
    2 3 Dec 0
    3 Man 12 Apr 0
    3 . 16 Apr 0
    3 . 15 Jun 0
    3 Woman 22 Jun 1
    4 Woman 9 Jan 0


    Any advice? Thanks in advance for your help!
    Last edited by Marley Mass; 13 Sep 2024, 05:13.

  • #2
    Assuming gender is a numeric variable with two levels and date is a proper Stata date variable:

    Code:
    gen tag= missing(gender)
    bys id tag (date): gen wanted= (gender!=gender[_n-1]) & _n>1 
    drop tag
    sort id date
    Last edited by Andrew Musau; 13 Sep 2024, 07:43.

    Comment


    • #3
      This worked perfectly. Thank you very much Andrew!

      Comment

      Working...
      X