Extract only quarter from a date in r

后端 未结 4 1802
被撕碎了的回忆
被撕碎了的回忆 2021-01-18 08:41

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         


        
相关标签:
4条回答
  • 2021-01-18 09:21

    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.

    0 讨论(0)
  • 2021-01-18 09:34

    lubridate package has the same function. We can use that also. I am using @Frank's DT

    DT[, qtr := lubridate::quarter(d)]
    
    0 讨论(0)
  • 2021-01-18 09:37

    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.)

    0 讨论(0)
  • 2021-01-18 09:37

    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.

    0 讨论(0)
提交回复
热议问题