Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract only quarter from a date in r

Tags:

date

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!

like image 409
Ye Tian Avatar asked Aug 29 '16 15:08

Ye Tian


1 Answers

There is a base R function, quarters, that more or less accomplishes what you want, though it prepends "Q". So

quarters(as.Date("2001-05-01"))
[1] "Q2"

If it is important to get rid of the "Q", you could use substr

substr(quarters(as.Date("2001-05-01")), 2, 2)
[1] "2"

Other date-related base R functions, such as weekdays and months can be found in help page ?quarters.

like image 115
lmo Avatar answered Oct 14 '22 06:10

lmo