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

From: Dimitri Liakhovitski <dimitri.liakhovitski_at_gmail.com>
Date: Thu, 19 May 2011 10:51:04 -0400


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

______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Thu 19 May 2011 - 14:59:20 GMT

This quarter's messages: by month, or sorted: [ by date ] [ by thread ] [ by subject ] [ by author ]

All messages

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 19 May 2011 - 16:50:08 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive