[R] Creating a "shifted" month (one that starts not on the first of each month but on another date)

Dimitri Liakhovitski dimitri.liakhovitski at gmail.com
Thu May 19 16:51:04 CEST 2011


Hello!
I have a data frame with dates. I need to create a new "month" that
starts on the 20th of each month - because I'll need to aggregate my
data later by that "shifted" month.
I wrote the code below and it works. However, I was wondering if there
is some ready-made function in some package - that makes it
easier/more elegant?
Thanks a lot!

# Example data:
mydf<-data.frame(mydate=seq(as.Date("2011-01-01"), length = 92, by = "day"))
(mydf)

### Creating a new variable that has one value before
### the 20th of each month and next value after it

mydf$daynum<-as.numeric(format(mydate,"%d"))
library(zoo)
mydf$yearmon<-as.yearmon(mydf$mydate)
(mydf); str(mydf)

mydf$newfactor<-NA
for(i in unique(mydf$yearmon)){	# looping through "yearmon" (important
because true data has many years of data)
	tempdf<-mydf[mydf$yearmon == i,]
	which.month<-which(unique(mydf$yearmon)==i)
	tempdf$newfactor[tempdf$daynum<20]<-which.month
	tempdf$newfactor[tempdf$daynum>19]<-(which.month+1)
	mydf[mydf$yearmon == i,]<-tempdf
}
(mydf)

-- 
Dimitri Liakhovitski
Ninah Consulting
www.ninah.com



More information about the R-help mailing list