Announcement

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

  • Simple by() and 'if' question

    I'm working with some historical data on NFL players. I want to create a dummy variable indicating whether a player is still active or not. Basically, I want Stata to produce active == 1 if a given player has an observation when year == 2019 and active == 0 otherwise.

    I feel like this should be simple, but I'm struggling to code this. What I tried was:

    Code:
    by id: gen active = 1 if year == 2019
    by id: replace active = 0 if year != 2019
    , but this just put active == 1 for all 2019 observations and active == 0 for all other observations regardless of whether the player was active in 2019.

    Does anyone have any advice here?

  • #2
    Maybe something like
    Code:
    bysort id: egen byte active = max(year == 2019)

    Comment


    • #3

      Code:
      bysort id (year) : gen active = year[_N] == 2019
      would presumably work too. The problem behind #1 is that by id: makes no difference to what is done, but the above does make a difference, as is true also of #2.

      Comment


      • #4
        You could do it in two steps:

        Code:
        generate active = year==2019
        bysort id: egen active_player = max(active)
        Edit:
        I didn't notice that Joseph Coveney posted something similar. Interesting to see if the egen function works that way, I didn't know that it did.
        Last edited by Karl Tjensvoll; 11 Nov 2019, 08:09.

        Comment


        • #5
          The pertinent syntax for the command (not function) egen runs

          max(exp) (allows by varlist)
          creates a constant (within varlist) containing the maximum value of exp.


          where the crucial detail is that you can feed max() an expression, which can be more complicated than a bare variable name. Thus

          Code:
          year == 2019
          is such an expression. It evaluates to 1 when true and 0 when false, which is what is needed here.

          Comment


          • #6
            Both Joseph and Nick's solutions worked for me. Thank you for your help!

            Comment

            Working...
            X