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
li
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
.
lubridate
package has the same function. We can use that also. I am using @Frank's DT
DT[, qtr := lubridate::quarter(d)]
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.)
dint
package also is suitable for that:
library("dint")
d=as.Date("2015-01-01")
get_quarter(d)
you can find more about this package here.