r - How to create monthly ordered Periods from datevector without looping? -


while difftime class pretty straight forward use when want obtain yearly or daily differences between dates. monthly differences weren't straight forward me. since r standard arithmetic allows substraction of date objects looping through vector possible, here´s solution avoids looping:

# generate reproducible example x<-seq(as.date("2010-11-15"),as.date("2011-05-20"),"months") y<-seq(as.date("2010-04-15"),as.date("2012-05-20"),"months") z<-seq(as.date("2012-08-15"),as.date("2013-05-20"),"months")  d <- c(z,x,y)  # function – suggestions welcome! getperiods <- function(datevector){ x <- floor((as.numeric(datevector)-as.numeric(min(datevector))) / 30) +1 return(x) }  # returns vector of monthly ordered periods. 

is there better, more native way it? example can use seq() in combination lenght() somehow? not able because seq´s "to" argument not allow vectors. feedback appreciated, besides hope may else...

the standard solution convert posixlt , start there.

getperiods2 <- function(datevector){   tmp <- as.posixlt(datevector)   tmp <- tmp$year*12 + tmp$mon    tmp - min(tmp) + 1 } 

this disregards differences in days, meaning difference between march 31 , april 1 1 in function, 0 in yours.

now months not of equal lengths, defining "monthly period" tricky business anyway. when run on years, might have leap year problem. monthly difference not objective : in definition, monthly difference 30 days, can argued about. people prefer 365/12 difference, stays correct when periods span multiple years.

see eg function:

> tt <- as.date(c("1998-01-01","2012-01-01")) > tt [1] "1998-01-01" "2012-01-01"  > getperiods(tt) [1]   1 171  > diff(getperiods(tt))/12 [1] 14.16667  > diff(getperiods2(tt))/12 [1] 14 

so according function, there 2 months more in 14 years there is. personal idea : use months months, not periods of 30 days. don't function wrong, it's approach that's more used. far i'm concerned, you're bound in trouble @ point.


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

aspxgridview - Devexpress grid - header filter does not work if column is initially hidden -

c# - How to execute a particular part of code asynchronously in a class -