Announcement

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

  • How to assign row number in a dataset to a new variable

    SHROUT RETX sprtrn event_date event_window
    2516605 0.00555951 0.00027547 -10 .
    2516605 -0.0051057 0.00528225 -9 .
    2516605 0.01555526 0.00035666 -8 .
    2516605 -0.0028723 0.00373984 -7 .
    2516605 -0.0001436 0.00189784 -6 .
    2516605 -0.0067038 -0.0022133 -3 .
    2516605 -0.0148939 -0.0036523 -2 .
    2516605 -0.0032213 -0.0028032 -1 .
    2516605 0.00224598 -0.0016543 0 0
    2516605 -0.0030787 0.00013443 4 .
    2516605 -0.0147525 -0.0044303 5 .
    2516605 0.00207242 0.00570143 6 .
    2516605 -0.0001382 0.00026927 7 .
    2516605 0.02433849 0.00767039 8 .

    Hi,

    I have the above dataset. I am trying to generate a variable which returns the row number where variable event_window == 0

    I need to retain a 3-day or a 5-day window around the event.

    Please advise.

    Thanks and regards,
    Kanishk


  • #2
    I need to retain a 3-day or a 5-day window around the event
    I do not understand this condition, but the observation number in Stata is indicated by "_n". So your command will be something like

    Code:
    gen wanted= _n if event_window == 0

    Note that the observation number depends on the sort order, so you may want sort your observations specifying some criterion using bysort, otherwise these values will be arbitrary.

    Comment


    • #3
      My guess is that whatever you want to do doesn't need a "row number" at all, as all the information required is already captured by existing variables.


      For example, this code gives a mean for a 3-day window centred on the event

      Code:
      egen wanted  = mean(RETX) if inrange(event_date, -1, 1), by(SHROUT)
      and this code spreads that result to the entire panel:


      Code:
      egen wanted  = mean(cond(inrange(event_date, -1, 1), RETX, ,), by(SHROUT)
      More at https://www.stata-journal.com/articl...article=dm0055

      Comment


      • #4
        There is a parenthesis missing in #3. And another typo. Sorry to anyone puzzled by either.

        Code:
         
         egen wanted  = mean(cond(inrange(event_date, -1, 1), RETX, .)), by(SHROUT)

        Comment

        Working...
        X