Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a numeric month to a month abbreviation

Tags:

date

r

People also ask

How do you convert month number to month name?

Please do as follows: Select a blank cell next to the sales table, type the formula =TEXT(A2*29,"mmm") (Note: A2 is the first number of the Month list you will convert to month name), and then drag the AutoFill Handle down to other cells. Now you will see the numbers (from 1 to 12) are converted to normal month names.


Take a look at the month.abb constant. For example, assume you have a vector of integers consisting of the number of the month, then you can use it to get the three letters abbreviation of the month name by doing:

> month <- c(12,3,6,2,3,7)
> month.abb[month]
[1] "Dec" "Mar" "Jun" "Feb" "Mar" "Jul"

If you need non-standard month abbreviation, then create your own month lookup vector:

#dummy data
df <- data.frame(month = c(1,3,5))
#months vector assuming 1st month is Jan.
mymonths <- c("Jan","Feb","Mar",
              "Apr","May","Jun",
              "Jul","Aug","Sep",
              "Oct","Nov","Dec")
#add abbreviated month name
df$MonthAbb <- mymonths[ df$month ]

#result
df
#   month MonthAbb
# 1     1      Jan
# 2     3      Mar
# 3     5      May

Use lubridate, construct a vector starting from a known month day:

Test: for these month numbers, assume Jan=1:

> m = c(1,2,6,7,9,10,11,12,0,99,NA)

do:

> require(lubridate)
> as.character(month(ymd(010101) + months(m-1),label=TRUE,abbr=TRUE))
 [1] "Jan" "Feb" "Jun" "Jul" "Sep" "Oct" "Nov" "Dec" "Dec" "Mar" NA   

where the (m-1) is because we are starting from a date in January.

To see how that compares:

> cbind(m,as.character(month(ymd(010101) + months(m-1),label=TRUE,abbr=TRUE)))
      m         
 [1,] "1"  "Jan"
 [2,] "2"  "Feb"
 [3,] "6"  "Jun"
 [4,] "7"  "Jul"
 [5,] "9"  "Sep"
 [6,] "10" "Oct"
 [7,] "11" "Nov"
 [8,] "12" "Dec"
 [9,] "0"  "Dec"
[10,] "99" "Mar"
[11,] NA   NA   

Note it interprets month numbers as mod-12 so 99 maps to 3 (99=3+(8*12)) and NA returns NA. Some of the answers already posted won't do this. -1 is Nov since 0 is Dec.


If English language abbreviations are acceptable, R has a built in constant month.abb vector of the abbreviated month names. Just use your numeric date to index that vector of abbreviate month names. For example, using dummy data:

set.seed(1)
df <- data.frame(A = runif(10), Month = sample(12, 10, replace = TRUE))

here are several options to index month.abb via Month:

> with(df, month.abb[Month])
 [1] "Mar" "Mar" "Sep" "May" "Oct" "Jun" "Sep" "Dec" "May" "Oct"
> df <- transform(df, MonthAbb = month.abb[Month])
> df
            A Month MonthAbb
1  0.26550866     3      Mar
2  0.37212390     3      Mar
3  0.57285336     9      Sep
4  0.90820779     5      May
5  0.20168193    10      Oct
6  0.89838968     6      Jun
7  0.94467527     9      Sep
8  0.66079779    12      Dec
9  0.62911404     5      May
10 0.06178627    10      Oct