[R] Function to get a sequence of months

Duncan Murdoch murdoch at stats.uwo.ca
Tue Sep 11 12:49:22 CEST 2007


On 11/09/2007 6:36 AM, Arun Kumar Saha wrote:
> Hi all,
> 
> I am looking for a function for following calculation.
> 
> start.month = "July"
> end.month = "January"
> 
> months = f(start.month, end.month, by=1)
> 
> * f is the function that I am looking for.
> 
> Actually I want to get months = c("July", "August",.............."January")
> 
> If start.month = 6 and end.month = 1 then I could use (not properly) seq()
> function and then I would get month as a vector with elements 6,5,4,3,2, and
> 1 by choosing "by=-1". Is there any function which can subsitute the seq()
> function in my case?

I don't think one already exists, but it's easy to write one:

 > cyclic_seq <- function(from, to, cycle=12) {
+     if (to < from) (from - 1):(to + cycle - 1) %% cycle + 1
+     else from:to
+ }
 > cyclic_seq(5, 1)
[1]  5  6  7  8  9 10 11 12  1
 > cyclic_seq(5, 5)
[1] 5
 > cyclic_seq(5, 6)
[1] 5 6

This makes various assumptions about the inputs (e.g. it would fail on 
cyclic_seq(20, 1) ); you might want to validate the inputs if you're 
giving it to other people.

Duncan Murdoch



More information about the R-help mailing list