0

I am currently working with dates in R and need to calculate the time difference between two quarters. I have used the zoo library to transform my dates into quarterly format, but I am struggling to calculate the difference between my dates.

Here is a sample code for reproducability:

sample_dataframe <- data.frame(First_Purchase_date = c(as.Date("2020-01-15"), as.Date("2019-02-10"),as.Date("2018-12-24")),Recent_Purchase_date = c(as.Date("2020-06-20"), as.Date("2020-10-10"), as.Date("2019-05-26")))

library(zoo)
#using zoo library to transform my dates into quarters
sample_dataframe$First_purchase_quarter <- as.yearqtr((sample_dataframe$First_Purchase_date), "%Y-%m-%d")
sample_dataframe$Recent_Purchase_quarter <- as.yearqtr((sample_dataframe$Recent_Purchase_date), "%Y-%m-%d")

What I want to achieve is to subtract Recent_Purchase_quarter from First_purchase_quarter to get a time difference in quarters.

So if Recent_Purchase_quarter is 2019 Q2 and First_Purchase_quarter is 2018 Q4 the result should be 2.

What would be the easiest way to get the time difference in quarters as described above?

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
emil_rore
  • 115
  • 1
  • 7
  • This post covers ways to calculate difference in terms of weeks, months, quarters and years https://stackoverflow.com/questions/14454476/get-the-difference-between-dates-in-terms-of-weeks-months-quarters-and-years – Ronak Shah Nov 05 '20 at 14:06

1 Answers1

2
#using zoo library to transform my dates into quarters
sample_dataframe$First_purchase_quarter <- as.yearqtr((sample_dataframe$First_Purchase_date), "%Y-%m-%d")
sample_dataframe$Recent_Purchase_quarter <- as.yearqtr((sample_dataframe$Recent_Purchase_date), "%Y-%m-%d")

sample_dataframe$diff <- (sample_dataframe[, 4] - sample_dataframe[, 3]) * 4
head(sample_dataframe$diff)
[1] 1 7 2
tester
  • 1,662
  • 1
  • 10
  • 16
  • Hey! Thanks a lot for your speedy reply! It seemed to have done the trick! Could you please elaborate why I have to multiply the calculation by 4 in order to get to the desired outcome? Thank you! – emil_rore Nov 05 '20 at 14:08
  • 1
    `yearqtr` thinks in years, so a timedifference of 0.25 equals one quarter, that's why it is multiplied by 4. You can find more information on it by running `?yearqtr` – tester Nov 05 '20 at 14:20