1

enter image description here

I would like to find the number of quarters dynamically from the date "03/31/2018". I have tried this to get 20th quarters. Similar way need to get other quarter numbers(e.g., 21 and 22) when data period increase.

as.numeric(as.Date("2018-03-31"))
# > [1] 17621
floor(as.numeric(Sys.Date()-17621)/92)-1
# > [1] 20

How can I edit the code above to get 21 and 22 dynamically when data period increases?

M--
  • 25,431
  • 8
  • 61
  • 93
Sona
  • 25
  • 4
  • Probably [this](https://stackoverflow.com/a/14455275/324364) question is a potential duplicate. – joran Aug 09 '23 at 21:17

2 Answers2

0

yearqtr objects represent a year and a quarter internally as the year plus 0 for the first quarter, 1/4 for the second quarter, 2/4 for the third quarter and 3/4 for the fourth quarter. Thus to find the number of quarters between two dates:

library(zoo)

d1 <- Sys.Date()
d2 <- as.Date("03/31/2018", "%m/%d/%Y")

4 * (as.yearqtr(d1) - as.yearqtr(d2))
## [1] 22

To find the year quarter 22 quarters ago

as.yearqtr(d1) - 22/4
## [1] "2018 Q1"

or to find the end of quarter date 22 quarters ago

as.Date(as.yearqtr(d1) - 22/4, frac = 1)
## [1] "2018-03-31"
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
0

Using lubridate

library(lubridate)
(interval(as.Date("2018-03-31"), today()) %/% months(3))
[1] 21
NicChr
  • 858
  • 1
  • 9