Announcement

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

  • Stata Coding

    Hi,

    I am trying to make a logical code that " Year will be 2016 if monthly is greater than 683 but less than 672." "Monthly" variable is in column in STATA where there are many months numbers are available.

    Can you please help me regarding this code?

    Thanks.

    Regards,

    Aryan

  • #2
    Well, 683 and 672 are Stata internal monthly dates representing December 2016 and January 2016. Rather than writing code that mentions these specific months, it probably makes more sense to use something more general that would apply to any months that happen to be in your data:

    Code:
    gen int year = year(dofm(monthly_variable))
    Do read -help datetime variables-. It's a lot to learn, but the time invested will be rapidly repaid.

    Comment


    • #3
      Hi Clyde,

      Many thanks for your quick reply. Actually, I have 720,000 observations in one file where "monthly" variable has a value ranging from 666 to 688. I would like to assign the year 2016 if "monthly" variable has a range of values between 683 and 672.

      Can you please help me in this regard?

      Regards,

      Aryan

      Comment


      • #4
        Well, the above code will do that, but it will also assign 2015 to months 666 through 671, and 2017 to 673 through 688. If you don't want that and would prefer for the variable to have missing values for the non-2016 months you can follow it with:

        Code:
        replace year = . if year != 2016

        Comment


        • #5
          Clyde's advice is spot on as usual.

          A more limited but still transparent version might be that the year is 2016 if (and only if) some monthly date is between ym(2016, 1) and ym(2016, 12). That way, Stata evaluates the two arguments and its role is understanding its own rules (it's very good at that) while the reader has a better chance of understanding the code, which people are very good at if it is self-explanatory.

          Comment

          Working...
          X