Announcement

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

  • Create a var with some conditions in a same column

    Hi,


    I want to create a var with some conditions in a same column. For example,

    This is the original data

    Id var1

    01 c
    01 d
    02 m
    02 f

    I want to create a var (var2) =1, if i have "c" and "d" in my Id "01"

    Id var1 var2

    01 c 1
    01 d 1
    02 m .
    02 f


    I hope you can help me
    Kind Regards,

    S.
    Last edited by sladmin; 14 Mar 2019, 10:58. Reason: anonymize original poster

  • #2
    Code:
    clear 
    input str2 (Id var1) 
    "01" "c"
    "01" "d"
    "02" "m"
    "02" "f"
    end 
    
    egen anyc = max(var1 == "c"), by(Id) 
    egen anyd = max(var1 == "d"), by(Id) 
    
    gen wanted = anyc & anyd 
    
    list, sepby(Id) 
    
         +----------------------------------+
         | Id   var1   anyc   anyd   wanted |
         |----------------------------------|
      1. | 01      c      1      1        1 |
      2. | 01      d      1      1        1 |
         |----------------------------------|
      3. | 02      m      0      0        0 |
      4. | 02      f      0      0        0 |
         +----------------------------------+

    Comment

    Working...
    X