0 votes
1 view
in R Programming by (5k points)

I have two dates let´s say 14.01.2013 and 26.03.2014.

I would like to get the difference between those two dates in terms of weeks(?), months(in example 14), quarters(4) and years(1).

Do you know the best way to get this?

1 Answer

0 votes
by (24.7k points)
edited by

To get the difference between dates in weeks, months, quarters, and years, you can use the following functions from the zoo and lubridate packages as follows:

Weeks:

library("zoo")

library("lubridate")

difftime(strptime("26.03.2014", format = "%d.%m.%Y"),

         strptime("14.01.2013", format = "%d.%m.%Y"),units="weeks")

Time difference of 62.28571 weeks

Months:

(as.yearmon(strptime("26.03.2014", format = "%d.%m.%Y"))-

    as.yearmon(strptime("14.01.2013", format = "%d.%m.%Y")))*12

[1] 14

Quarters:

(as.yearqtr(strptime("26.03.2014", format = "%d.%m.%Y"))-

    as.yearqtr(strptime("14.01.2013", format = "%d.%m.%Y")))*4

[1] 4

Years:

year(strptime("26.03.2014", format = "%d.%m.%Y"))-

  year(strptime("14.01.2013", format = "%d.%m.%Y"))

[1] 1

If you want to explore more in R programming then watch this R programming tutorial for beginner:

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...