Announcement

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

  • Count observations in periods

    Hi,

    Im working with a dataset that contains 120 funds (id=1,120) and I have constructed two periods (period1 and period2). I now want to create a new variable that counts how many observations I have in each period.
    See below for dataex.
    In this case I would like the new variable obs_p1 to take the value 7 and the new variable obs_p1 to take the value 5.

    Any suggestions about the code I need?
    Thanks!

    ----------------------- copy starting from the next line -----------------------
    [CODE]
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input float
    (id period1 period2)
    1 1 0
    1 1 0
    1 1 0
    1 1 0
    1 1 0
    1 1 0
    1 1 0
    1 0 1
    1 0 1
    1 0 1
    1 0 1
    1 0 1

  • #2
    Hello Olle,

    One way to do this is:

    egen obs_p1 = count(id), by (period1)
    replace obs_p1 = 0 if period2 == 1
    egen obs_p2 = count(id), by(period2)
    replace obs_p2 = 0 if period1 == 1

    I am sure that there is a way better way... but this is what I quickly came up with!

    Cheers,


    Scott
    Last edited by Scott Knowles; 27 Nov 2019, 06:13. Reason: edited "regen" to "egen"

    Comment


    • #3
      In this example

      Code:
      bysort period1 : gen wanted = _N
      gives the answer wanted. I suspect that you need something more general such as

      Code:
      bysort id period1 : gen wanted = _N

      Comment

      Working...
      X