[R] expanding 1:12 months to Jan:Dec

Gavin Simpson gavin.simpson at ucl.ac.uk
Thu Aug 20 09:41:42 CEST 2009


On Thu, 2009-08-20 at 08:14 +0100, Liviu Andronic wrote:
> Dear R users
> I would like to do some spreadsheet style expansion of dates. For
> example, I would need to obtain a vector of months. I approached in an
> obviously wrong way:
> > paste(01:12)
>  [1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10" "11" "12"
> > as.Date(paste(01:12), "%m")
>  [1] NA NA NA NA NA NA NA NA NA NA NA NA
> 
> to subsequently format(.., "%b"). Other than writing the months
> manually, could anyone suggest an easier way to obtain such a list?
> Liviu

I think as.Date is probably not the best way to approach this as these
aren't really dates - all you have is the month.

R has some built in constants, including the abbreviated month names.
See ?month.abb :

mon <- 01:12
mon <- factor(mon, labels = month.abb)
mon

as.character(mon) ## it you want these as strings not a factor

Notice also that starting from characters doesn't get the right answer.
Compare mon above with the output from below.

mon2 <- as.character(01:12)
mon2 <- factor(mon2, labels = month.abb)
mon2

With mon, using the month numbers as numerics keeps the ordering. If
your data are characters, then replace the first line in the mon example
with (something like):

mon <- as.numeric(my.months)

where my.months is your vector of months.

FYI, should you need the full names at any point, there is another
constant 'month.name' that fulfils that requirement. See ?month.abb

G
-- 
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
 Dr. Gavin Simpson             [t] +44 (0)20 7679 0522
 ECRC, UCL Geography,          [f] +44 (0)20 7679 0565
 Pearson Building,             [e] gavin.simpsonATNOSPAMucl.ac.uk
 Gower Street, London          [w] http://www.ucl.ac.uk/~ucfagls/
 UK. WC1E 6BT.                 [w] http://www.freshwaters.org.uk
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%




More information about the R-help mailing list