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
This is a part of the course
“Intermediate R for Finance”
Exercise 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()
ondates
to see how many days from January 1, 1970 it has been. - Finally, subtract
origin
fromdates
to confirm the results! (Notice how recycling is used here!)
Hands-on interactive exercise
Have a go at this exercise by completing this sample 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
___
This exercise is part of the course
Intermediate R for Finance
Learn about how dates work in R, and explore the world of if statements, loops, and functions using financial examples.
Welcome! Before we go deeper into the world of R, it will be nice to have an understanding of how dates and times are created. This chapter will teach you enough to begin working with dates, but only scratches the surface of what you can do with them.
Exercise 1: An introduction to dates in RExercise 2: What day is it?Exercise 3: From char to dateExercise 4: Many datesExercise 5: Date formats and extractor functionsExercise 6: Date formats (1)Exercise 7: Date formats (2)Exercise 8: Subtraction of datesExercise 9: months() and weekdays() and quarters(), oh my!What is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.