Aidas
Aidas

Reputation: 63

How to format the quarter date in R?

I have a df as follows:

df

ID   Date
1    2000/01/12
2    2015/06/11
3    2013/09/10
4    2002/01/07
5    2006/04/05

I wanted to add a third column representing quarters with the code:

df$quarter <- paste(format(df$Date, "%y"), 
                  sprintf("%02i", (as.POSIXlt(df$Date)$mon) %/% 3L + 1L), sep="/")

and received the following output:

ID   Date          quarter
1    2000/01/12    00/04
2    2015/06/11    15/04
3    2013/09/10    13/04
4    2002/01/07    02/03
5    2006/04/05    06/02

My question is how can I change the format of the quarter column to have the following output:

ID   Date          quarter
1    2000/01/12    2000q4
2    2015/06/11    2015q4
3    2013/09/10    2013q4
4    2002/01/07    2002q3
5    2006/04/05    2006q2

I don't know how to properly modify my code! Thank you!

Upvotes: 2

Views: 628

Answers (1)

akrun
akrun

Reputation: 886948

We can use as.yearqtr from zoo and then replace the space followed by Q with q using sub

library(zoo)
df$quarter <- sub("\\s+Q", "q", as.yearqtr(df$Date, '%Y/%d/%m'))
df$quarter
#[1] "2000q4" "2015q4" "2013q4" "2002q3" "2006q2"

Or as @G.Grothendieck suggested in the comments

df <- transform(df, Date = format(as.yearqtr(Date, '%Y/%d/%m'), "%Yq%q"))

data

df <- structure(list(ID = 1:5, Date = c("2000/01/12", "2015/06/11", 
"2013/09/10", "2002/01/07", "2006/04/05")),
class = "data.frame", row.names = c(NA, 
-5L))

Upvotes: 3

Related Questions