Announcement

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

  • Set up a count variable with a filter


    Hi all, i would like to add a new variable with a counter. For the following dataset I would like to add a 4th variable which will be the mentioned counter. The counter should count the number of B observations for a given A observation when the filter equals 1. For example: the first count value should be 2 because the observation "1" in B occurs twice for the observation "1" in A given that the filter equals 1. * Example generated by -dataex-. To install: ssc install dataex clear input int(A B filter) 1 1 1 1 2 0 1 3 0 1 2 0 1 3 1 1 1 1 1 4 0 2 4 0 2 2 1 2 3 1 2 3 0 3 1 0 3 2 0 end I would appreciate any kind of help. Thank you very much.

  • #2

    Sorry for the visualisation. I hope this time it works. Code: * Example generated by -dataex-. To install: ssc install dataex clear input int(A B wanted) 1 1 1 1 2 0 1 3 0 1 2 0 1 3 1 1 1 1 2 4 0 2 2 1 2 3 1 2 3 0 3 1 0 3 2 0 end

    Comment


    • #3
      A B filter
      1 1 1
      1 2 0
      1 3 0
      1 2 0
      1 3 1
      1 1 1
      2 4 0
      2 2 1
      2 3 1
      2 3 0
      3 1 0
      3 2 0

      Comment


      • #4
        Here is code using your example data that seems to do what you want.
        Code:
        . clear
        
        . input int(A B filter)
        
                    A         B    filter
          1. 1 1 1
          2. 1 2 0
          3. 1 3 0
          4. 1 2 0
          5. 1 3 1
          6. 1 1 1
          7. 2 4 0
          8. 2 2 1
          9. 2 3 1
         10. 2 3 0
         11. 3 1 0
         12. 3 2 0
         13. end
        
        . bysort A B : egen count = total(filter==1)
        
        . list, noobs sepby(A B)
        
          +------------------------+
          | A   B   filter   count |
          |------------------------|
          | 1   1        1       2 |
          | 1   1        1       2 |
          |------------------------|
          | 1   2        0       0 |
          | 1   2        0       0 |
          |------------------------|
          | 1   3        1       1 |
          | 1   3        0       1 |
          |------------------------|
          | 2   2        1       1 |
          |------------------------|
          | 2   3        0       1 |
          | 2   3        1       1 |
          |------------------------|
          | 2   4        0       0 |
          |------------------------|
          | 3   1        0       0 |
          |------------------------|
          | 3   2        0       0 |
          +------------------------+

        Comment

        Working...
        X