Ye Tian Ye Tian - 3 months ago 12
R Question

Extract only quarter from a date in r

I would like to extract ONLY the quarter from a date, e.g., to get an integer 1 from the date "2003-02-08". I have been trying something along this line

library(mondate)
as.yearqtr(dat$DATE)



"2003 Q1"


as.character(as.yearqtr(dat$DATE))[1]



"2003 Q1"


which hasn't been giving my desired result. Of course I can write conditions as follows

library(data.table)
data$DATE = as.Date(data$DATE, format='%d%b%Y')
data$month=month(data$DATE)
setDT(data)[month==1, quarter:=1]
...


This will work, but is not elegant at all. Is there a more beautiful way of doing this?

Thank you lmo and user2100721! I really wish I could accept all of the answers!

Answer

I would do:

# example data
DT = data.table(id = 1:10, d = as.IDate("2003-02-08") + seq(100, by=50, length.out=10))

DT[, qtr := quarter(d)]

    id          d qtr
 1:  1 2003-05-19   2
 2:  2 2003-07-08   3
 3:  3 2003-08-27   3
 4:  4 2003-10-16   4
 5:  5 2003-12-05   4
 6:  6 2004-01-24   1
 7:  7 2004-03-14   1
 8:  8 2004-05-03   2
 9:  9 2004-06-22   2
10: 10 2004-08-11   3

The quarter function is provided by data.table and works on both Date and IDate vectors. (IDate uses integer storage.)

Comments