Tomikuz
Tomikuz

Reputation: 37

Month Number to Month Name

I am trying to convert a month number to a month name in Stata, i.e. 12 to Dec (or December) and so on and so on.

I know I can do a set of replace ifs. Te problem with that is that I have to make this fix in multiple places and thus my code will become ginormous.

In SAS I would do something like this

Month_Str = put(Month,monname3.);  

Is there an equivalent function in Stata?

Upvotes: 0

Views: 3409

Answers (2)

Nick Cox
Nick Cox

Reputation: 37278

I can easily imagine why you, or your users, might prefer to see (say) Jan or January rather than 1 in output. I can less easily imagine why you might want to store month of the year as strings. They won't sort in any natural order, they aren't more useful for graphics or tables for that reason, and they take up more memory.

To see months in this way you can define value labels. Suppose you have month as an integer variable with values 1 to 12:

tokenize "`c(Mons)'" 

forval m = 1/12 { 
    label def month `m' "``m''", add 
} 

label val month month 

Stata doesn't have a inbuilt function to map month number to month name string, and I don't recall that being asked for, which fits with a prejudice that it isn't really needed or helpful. To provide your own display, you need a few lines of code, but neither this solution nor that of @JR96 in their answer leads to "ginormous" code.

An advantage of this approach is that you can use names or abbreviations appropriate to any language, starting not from c(Mons) but from your own preferred lists of names or abbreviations.

EDIT. If month is a variable containing month number 1 to 12, then here is some more technique to create a string variable containing the name. As said, value labels are usually a better idea.

gen month_s = word("`c(Mons)'", month) 
gen month_l = word("`c(Months)'", month) 
gen month_fr = word("janvier fevrier mars avril mai juin juillet août septembre octobre novembre décembre", month) 

Upvotes: 2

JR96
JR96

Reputation: 973

Here is one solution. You could use Stata's c-class (help creturn) to get a chronologically-ordered list of months. Then use their place in the list to populate a string value.

//Sample Data
clear 
set obs 10
gen month = runiformint(1,12)

gen month_str = ""
forval m = 1/12 {
    local month_full: word `m' of `c(Months)'
    replace month_str = "`month_full'" if month == `m'
}

Here you could instead use c(Mons) which would give you the 3 letter abbreviation (e.g. Aug for August). I am curious if I someone has another approach. I generally do this numeric to string month mapping often, so I just keep a dta saved that I will merge on m:1.

Upvotes: 1

Related Questions