Announcement

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

  • egen if else max min

    Hi everyone,

    I wish to write a code that finds the maximum of the variable "difference" if the variable "negpost" is equal to 1, the minimum of the variable "difference" if the variable "negpost" is equal to -1, and just a dot if "difference" is equal to another value than -1 or 1 (see attached file for screenshot of data). This must also be done by "our_director_id" "permno1" and "event_date"

    I wrote the following code, but it doesn't seem to work:

    if negpost==1 {
    by our_director_id permno1 event_date: egen minmax = max(difference)
    }
    else if negpost==-1 {
    by our_director_id permno1 event_date: minmax = min(difference)
    }

    Would be really great if someone of you could explain me what I'm doing wrong. Thanks a lot.

    Aurele

  • #2
    The if statement is not what you need. See

    http://www.stata.com/support/faqs/pr...-if-qualifier/

    An egen is probably intended in the second long command, but if you start with that idea I don't think you can recast the code easily.

    So I think you need something else. Consider

    Code:
    bysort our_director_id permno1 event_date (difference): gen minmax = difference[_N] if negpost == 1
    by our_director_id permno1 event_date: replace minmax = difference[1] if negpost == -1
    This assumes that (a) negpost is constant within distinct groups of our_director_id permno1 event_date
    (b) that difference is never missing


    Alternatively, but with assumption (a) only, this should work:

    Code:
    by our_director_id permno1 event_date: egen max = max(difference) if negpost==1
    by our_director_id permno1 event_date: egen min = min(difference) if negpost==-1
    gen minmax = min(min, max)
    Last edited by Nick Cox; 24 Nov 2015, 13:15.

    Comment


    • #3
      This is exactly what I needed! Thanks a bunch!

      Comment


      • #4
        Good. Now please promise never to use photos of data listings again! http://www.statalist.org/forums/help#stata

        Comment

        Working...
        X