Announcement

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

  • bysort gen n = _n with if criteria not producing 1,2,3,4.... etc

    Hi there,

    I have a dataset that looks like this, where I have generated n and N by using:
    bysort ID: gen n=_n
    bysort ID: gen N=_N
    ID Dummy n N
    1 0 1 4
    1 0 2 4
    1 1 3 4
    1 1 4 4
    2 0 1 1
    3 1 1 1
    4 1 1 3
    4 0 2 3
    4 1 3 3
    What I now want to do is generate n and N the same way, but only if the dummy = 1.
    I tried this command:

    bysort ID: gen n=_n if Dummy ==1
    bysort ID: gen N=_N if Dummy ==1

    and it produces something like this (basically the same table but with missings where Dummy =0):
    ID
    Dummy
    n N
    1 0 . .
    1 0 . .
    1 1 3 4
    1 1 4 4
    2 0 . .
    3 1 1 1
    4 1 1 3
    4 0 . .
    4 1 3 3

    But what I really want is it to ignore the observations where Dummy = 0 and do the 'count' or labeling or whatever it is only on those where dummy =1.
    So that it looks like this:
    ID Dummy n N
    1 0 . .
    1 0 . .
    1 1 1 2
    1 1 2 2
    2 0 . .
    3 1 1 1
    4 1 1 2
    4 0 . .
    4 1 2 2

    Could somebody advise how to do this?

    Many thanks,
    A


  • #2
    Code:
     
    . clear 
    
    . input ID        Dummy   
    
                ID      Dummy
      1. 1       0       
      2. 1       0       
      3. 1       1       
      4. 1       1       
      5. 2       0       
      6. 3       1       
      7. 4       1       
      8. 4       0       
      9. 4       1       
     10. end 
    
    . sort ID, stable 
    
    . by ID : gen n = sum(Dummy) if Dummy 
    (4 missing values generated)
    
    . by ID : egen N = total(Dummy) if Dummy 
    (4 missing values generated)
    
    . list, sepby(ID) 
    
         +--------------------+
         | ID   Dummy   n   N |
         |--------------------|
      1. |  1       0   .   . |
      2. |  1       0   .   . |
      3. |  1       1   1   2 |
      4. |  1       1   2   2 |
         |--------------------|
      5. |  2       0   .   . |
         |--------------------|
      6. |  3       1   1   1 |
         |--------------------|
      7. |  4       1   1   2 |
      8. |  4       0   .   . |
      9. |  4       1   2   2 |
         +--------------------+

    Comment


    • #3
      Ty

      Comment

      Working...
      X