Announcement

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

  • How to create a date variable from month? String Variable

    Hi
    I have a query my variable is in the following format: 1901m12, 1902m1 and so on.
    I want to separate this and create a monthly variable where January=1, February=2 and so on. What is the command that I could use (This is a string variable)
    The code I used is :
    gen date1=monthly(date,"YM")
    gen date2 = dofm(date1)
    format date2 %d
    But this is not getting the required results.
    My data on the dataex command is as follows
    [CODE]
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input int month
    -697
    -696
    -695
    -694
    -693
    -692
    -691
    -690
    -689
    -688
    -687
    -686
    -685
    -684
    -683
    -682
    -681
    -680
    -679
    -678
    -677
    -676
    -675
    -674

  • #2
    Your post is a bit confusing, because the code you show refers to variables date, date1, and date2, that do not appear in your example. The example contains a different variable, called month which you do not talk about.

    Nevertheless, I assume that you have this variable named month which is a Stata internal format monthly date variable and you want to extract from it the month of year (which is a number from 1 to 12). The code below does this:

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input int month
    -697
    -696
    -695
    -694
    -693
    -692
    -691
    -690
    -689
    -688
    -687
    -686
    -685
    -684
    -683
    -682
    -681
    -680
    -679
    -678
    -677
    -676
    -675
    -674
    end
    format month %tm
    
    gen month_of_year = month(dofm(month))
    It is not a good idea to name your variable month, for two reasons. There is a Stata function called -month()- (which, in fact, is used in the code above) and in some contexts it might potentially confuse Stata's processor to have a variable name that is the same as a function or Stata command. Best to avoid that kind of clash of names. The second, and more important reason, is that it isn't a correct description of what the variable contains. I'd call it month_year, or month_and_year, or m_y, or something like that, to distinguish it from a simple 1-12 variable containing only the month of the year.

    So good programming practice is to avoid variable names that match any Stata command or function names, and to use names that are good descriptions of what they contain. It makes debugging and maintenance a whole lot easier.

    Comment


    • #3
      Thank you so much this helped!

      Comment

      Working...
      X