Reputation: 872
I want to split monthly date range into quarterly basis period. My Date Variable is built with as.yearmonth:
> data$DATES
jul. 2014
ago. 2014
sep. 2014
...
...
jun. 2016
jul. 2016
ago. 2016
sep. 2016
How should I do it? cut function works with dates? I don't want to do this manually.
Upvotes: 1
Views: 3745
Reputation: 269624
Assuming by yearmonth you meant "yearmon"
class from zoo as per Note at the end:
1) yearqtr Convert to "yearqtr"
class (also in zoo, like "yearmon"
) and split on that. No additional packages beyond those you are already using are needed.
split(data, as.yearqtr(data$DATES))
or if you want to aggregate it, rather than split it:
aggregate(values ~ DATES, transform(data, DATES = as.yearqtr(DATES)), mean)
2) cut If you want to use cut
then:
split(data, cut(as.Date(data$DATES), "quarter"))
Note: Test data in reproducible form:
library(zoo)
data <- data.frame(DATES = as.yearmon(2014) + 0:11/12, values = 1:12) # test data
Upvotes: 3
Reputation: 2950
Lubridate has a quarter function. Check it out:
library(lubridate)
x <- ymd(c("2012-03-26", "2012-05-04", "2012-09-23", "2012-12-31"))
quarter(x)
quarter(x, with_year = TRUE)
Then the only thing you have to do is sort out your date formats so that they are understood.
Upvotes: 7