Get startedGet started for free

Introduction to dates

1. Introduction to dates

Welcome to working with dates and times in R. In this course you'll master importing, manipulating and computing with dates and times to explore weather, schedule meetings and calculate reigns of monarchs. In this chapter you'll learn about R's built-in objects for handling dates and times.

2. Dates

Let's start with dates. Where I grew up in New Zealand we always put day of month first, then month, then year. But in the US the convention is month first, then day of month, then year. This can get confusing, surely one of them must be more correct?

3. The global standard numeric date format

It turns out there is a global standard called ISO 8601, that specifies the correct way to share dates to avoid all confusion. It says order the components in decreasing units, that is, year, month then day. Turns out both the US and New Zealand conventions are wrong. All these other formats also don't comply with ISO 8601. Please, don't try to give R dates painted on a black cat.

4. ISO 8601 YYYY-MM-DD

The ISO 8601 standard specifies the order of the components, but also a few other details about the date. For example, each component has a fixed number of digits: year has four and day and month two. If you only need one digit for the day or month, you must pad it with leading zeros. You don't have to use separator in the ISO standard but if you do it must be a dash in dates. So, the date, the 1st of January 2011, in ISO 8601 standard is 2011 (dash) 01 (dash) 01.

5. Dates in R

If you have a date in ISO 8601 format, it still takes a little work to get R to recognize it as a date. If you try to just input it on the console, R will interpret the dashes as subtraction and you'll end up with something a little surprising. You might think using quotes will help. It certainly looks like a date, but R still thinks it's just a character string. The secret to getting R to recognize dates, is telling it explicitly "this is a date" with the as (dot) Date function. as (dot) Date takes a character string and turns it into a date object. It will only work with dates in the ISO order, but you'll see how to handle other formats in Chapter 2. There are also a couple of packages that will automatically import dates in a wider range of formats. You'll see two examples in the exercises: readr and anytime

6. Let's practice!

Alright, let's get some dates into R.

Create Your Free Account

or

By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.