Announcement

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

  • max and if together

    I want to generate a binary variable name “eldest” as follows:

    if a person is the most aged person in a household, then eldest =1,
    if a person is NOT the most aged person in a household, then eldest =0

    The command I used is as follows:

    gen eldest=0
    bysort hhid: replace eldest=1 if max(age)

    by its says "Invalid syntax"

    What is the problem?

    What is the correct way to do it?

    Thank You

  • #2
    Code:
    bysort hhid (age): gen wanted = age == age[_N]

    Comment


    • #3
      It worked @Snilsberg. Thanks for the help.

      But I am unable to understand the code in detail.

      Would you mind explaining the code !!!

      Comment


      • #4
        What does [_N] means?

        Comment


        • #5
          wanted is the last observation (_N) within hhid sorted by age

          Comment


          • #6
            Every Stata user should learn how to use sorting by groups and the system variables _n and _N. Therefore Oyvind's solution is preferred.

            A simpler and more lengthy solution with -egen- would be something like:

            Code:
            egen maxage = max(age), by(hhid)
            gen maxagedummy = age==maxage

            Comment


            • #7
              Snilsberg and Joro, thanks for your cooperation. It was really helpful for me.

              Comment


              • #8
                Constructions like -bysort hhid: replace eldest=1 if max(age)- would work if Stata understood English. But Stata doesn't understand any natural languages, it understands only its own artificial language. That language is, by now, huge, and probably few if any people know every aspect of it. Nevertheless, there is a core part of Stata that everyone who uses it with any regularity needs to know in order to be productive in it. The online PDF documentation includes a good introduction to that. William Lisowski has frequently posted suggested introductory reading. You can find it at #5 at https://www.statalist.org/forums/for...uplicate-dates. I highly recommend following the advice there to become familiar with the general approach to Stata and to learn the "bread and butter" commands. That investment of your time will bring enormous returns.

                Comment


                • #9
                  Thanks a lot Clyde Schechter

                  Comment

                  Working...
                  X