Reputation: 1667
I would like to turn a monthly time series into a quarterly one, by only keeping 4 values from the year. I have a date column in a dataframe as an integer in this monthly format:
192707
192708
192709
....
I have converted it to date format:
library(zoo)
df$date<-as.Date(as.yearmon(as.character(df$date), format = '%Y%m'), frac=1)
Next I was thinking to keep only 4 months of the year (Jan, Apr, Jul, Oct) with something like this, but I am not sure how to exactly do this:
df<-subset(df, month(df$date)==1 | month(df$date)==4 |
month(df$date)==7 | month(df$date)==10)
Is there a way to extract the month from the date column?
Upvotes: 1
Views: 2694
Reputation: 20085
Another option could be using month number i.e. 1, 4, 7, 10
is as:
df[month(df$date) %% 3 == 1,]
In this one can avoid comparison on name. Hence it should be quick.
Note: I must mention here that OP has used zoo
package.
Upvotes: 2
Reputation: 5191
Yes, you are very close. Using the months
function gives the full name of the month of the date, then using month.name
we can get just the 4 months you want:
df <- df[months(df$date) %in% month.name[c(1,4,7,10)], ]
Upvotes: 4