Get startedGet started for free

An introduction to dates in R

1. An introduction to dates in R

In this intermediate R for finance course, you will

2. What will you learn?

apply what you learned in the introductory course to work up to more fun and complicated examples. Along the way, you will learn core data science tools such as if statements, loops, and functions, with the majority of examples being related to finance. In this chapter, you will be introduced to the basics of how R handles dates. For financial data, dates can be as simple as regular yearly data, or as complicated as high frequency millisecond data, so it is important to understand how R represents them internally. Let's get started!

3. Today's date

The easiest way to get started with dates is by asking R what today's date is. The Sys-dot-Date function, short for System Date, does exactly this. When you execute this function, R returns the current date. Here it returned March 14th, 2017 in the standard form of year, month, day. What is the class of this object? The class function tells us that it is a Date.

4. Date classes

In R, there are two main classes for this type of data. One of them, as you just saw, is Date. Date is used to store calendar dates. For finer resolution, the POSIX classes are used. The two classes POSIXlt and POSIXct together allow you to hold the date, the current time, and the time zone. For simplicity, this course will focus mainly on the Date class, but I highly encourage you to check out other DataCamp courses such as Manipulating Time Series Data in R with xts and zoo to learn about other classes.

5. Creating dates

One of the most common ways of creating Date objects is from character vectors. In the example, you can see that as-dot-Date is used to convert the character date into an R Date object. The date, March 4th, 1957, is the first time the S&P 500 opened in the form that it is in today. While it might not look like much happened, sp500 birthday is now of class Date, and is stored internally as the number of days since January 1st, 1970. In the exercises, you dig into how different types of dates are stored internally.

6. Let's practice!

Great! Now that you've been introduced to dates, you know enough to work through the first few exercises. Have fun!