CommencerCommencer gratuitement

Subtraction of dates

Just like with numerics, arithmetic can be done on dates. In particular, you can find the difference between two dates, in days, by using subtraction:

today <- as.Date("2017-01-02")
tomorrow <- as.Date("2017-01-03")
one_year_away <- as.Date("2018-01-02")

tomorrow - today
Time difference of 1 days

one_year_away - today
Time difference of 365 days

Equivalently, you could use the difftime() function to find the time interval instead.

difftime(tomorrow, today)
Time difference of 1 days

# With some extra options!
difftime(tomorrow, today, units = "secs")
Time difference of 86400 secs

Cet exercice fait partie du cours

Intermediate R for Finance

Afficher le cours

Instructions

  • A vector of dates has been created for you.
  • You can use subtraction to confirm that January 1, 1970 is the first date that R counts from. First, create a variable called origin containing "1970-01-01" as a date.
  • Now, use as.numeric() on dates to see how many days from January 1, 1970 it has been.
  • Finally, subtract origin from dates to confirm the results! (Notice how recycling is used here!)

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de code.

# Dates
dates <- as.Date(c("2017-01-01", "2017-01-02", "2017-01-03"))

# Create the origin
origin <- ___

# Use as.numeric() on dates
___

# Find the difference between dates and origin
___
Modifier et exécuter le code