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!
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With