Announcement

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

  • Generating a cumulative count variable based on a group of variables

    Hi! I am wondering whether there is (as I am sure there is) an easy way of generating a cumu lative count variable based on several other values. What I want is a cumulative count of the number of floods over the past year within each group (id), as is shown by the *cumulative_count* variable that i added. There are sometimes several id's at the same time in the same country, so the cumulative variable needs to address this.

    cntry year mn id flood *cumulative_count*
    India 1996 1 78 0 0
    India 1996 2 78 0 0
    India 1996 3 78 0 0
    India 1996 4 78 0 0
    India 1996 5 78 0 0
    India 1996 6 78 1 1
    India 1996 7 78 1 2
    India 1996 8 78 1 3
    India 1996 9 78 0 3
    India 1996 10 78 1 4
    India 1996 11 78 1 5
    India 1996 12 78 0 5
    India 1997 1 78 0 0
    India 1997 2 78 0 0
    India 1997 3 78 0 0
    India 1997 4 78 0 0
    India 1997 5 78 0 0
    India 1997 6 78 1 1
    India 1997 7 78 1 2
    India 1997 8 78 1 3
    India 1997 9 78 1 4
    India 1997 10 78 0 4
    India 1997 11 78 0 4
    India 1997 12 78 1 5
    India 1998 1 78 0 5
    India 1998 2 78 0 5
    India 1998 3 78 0 5
    India 1998 4 78 0 5

    Thanks for any help!

  • #2
    Code:
    bysort cntry year (mn): gen cumulative_count = sum(flood)
    sum() gives cumulative or running sums.

    Comment


    • #3
      Thank you very much Nick! Do you also know what I should do if I wanted to make a running sum of the number of floods over the past 6 months within each id-group - not restricting it to each year?

      Comment


      • #4
        That's just the difference between two cumulative sums, so an application of the same principles:

        Code:
          
        bysort cntry (year mn): gen ever_count = sum(flood)
        by cntry: gen last6 = ever_count - ever_count[_n-5]

        Comment


        • #5
          Aha! Thanks again.

          Comment

          Working...
          X