Because R stores datetime objects as numbers, you can do various operations on dates.

Addition and subtraction in R

Because R stores objects of class POSIXct as the number of seconds since the epoch (usually the start of 1970), you can do addition and subtraction by adding or subtracting seconds. It’s more common to add or subtract days from dates, so it’s useful to know that each day has 86,400 seconds.

> 24*60*60
[1] 86400

So, to add seven days to the Apollo moon landing date, use addition, just remember to multiply the number of days by the number of seconds per day:

> xct + 7*86400
[1] "1969-07-27 20:17:39 UTC"

After you know that you can convert any duration to seconds, you can add or subtract any value to a datetime object. For example, add three hours to the time of the Apollo moon landing:

> xct + 3*60*60
[1] "1969-07-20 23:17:39 UTC"

Similarly, to get a date seven days earlier, use subtraction:

> xct - 7*86400
[1] "1969-07-13 20:17:39 UTC"

Comparison of dates in R

Similar to the way that you can add or subtract states you can also compare dates with the comparison operators, such as less than (<) or greater than (>).

Say you want to compare the current time with any fixed time. In R, you use the Sys.time() function to get the current system time:

> Sys.time()
[1] "2012-03-24 10:12:52 GMT"

Now you know the exact time when we wrote this sentence. Clearly when you try the same command you will get a different result!

Now you can compare your current system time with the time of the Apollo landing:

> Sys.time() < xct
[1] FALSE

If your system clock is accurate, then obviously you would expect the result to be false, because the moon landing happened more than 40 years ago.

The comparison operators are vectorized, so you can compare an entire vector of dates with the moon landing date. Try to use all your knowledge of dates, sequences of dates, and comparison operators to compare the start of several decades to the moon landing date.

Start by creating a POSIXct object containing the first day of 1950. Then use seq() to create a sequence with intervals of ten years: