Announcement

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

  • Generate a counter summing the occurrences of an element in various variables.

    Hello dear Statamasters,

    I met an issue trying to generate a counter for my data frame.
    I want to generate the yearly number of occurrences where some country-code (gwno) appears in the various variables (here gwno_a1, gwno_a2 and gwno_b1).

    Here, an example of the form of my dataset :

    year gwno_a1 gwno_a2 gwno_b1
    1985 750 625 2
    1985 530 . 666
    1985 625 . 750
    1985 645 700 811
    1986 630 . 750
    1986 530 . 666
    1986 811 . 645
    1986 560 . 625

    And I want to obtain something that looks like the following dataset :

    year gwno count
    1985 2 1
    1985 530 1
    1985 625 2
    1985 645 1
    1985 666 1
    1985 700 1
    1985 750 2
    1985 811 1
    1986 530 1
    1986 560 1
    1986 625 1
    1986 630 1
    1986 645 1
    1986 666 1
    1986 750 1
    1986 811 1


    Thank you so much for your help !

  • #2
    Code:
    clear 
    input year gwno_a1 gwno_a2 gwno_b1
    1985 750 625 2
    1985 530 . 666
    1985 625 . 750
    1985 645 700 811
    1986 630 . 750
    1986 530 . 666
    1986 811 . 645
    1986 560 . 625
    end 
    
    bysort year : gen id = _n 
    reshape long gwno, i(year id) string 
    drop _j id
    drop if gwno == .
    contract year gwno, freq(count)
    l

    Comment


    • #3
      Thank you so much Nick !
      That very concise piece of code will help me a lot !

      Comment

      Working...
      X