R Tutorial: Date formats and extractor functions

Описание к видео R Tutorial: Date formats and extractor functions

Want to learn more? Take the full course at https://learn.datacamp.com/courses/in... at your own pace. More than a video, you'll learn hands-on coding & quickly apply skills to your daily work.

---
R is picky about the format of dates that it accepts. The default format is the ISO 8601 standard in the form of year, month, day separated by a dash. If that fails, R will also check year, month, day separated by a forward slash. If both of these fail, then R will complain that you aren't using a standard format. You will often run into dates in the real world that aren't in this standard format, so what then? as.Date() has a flexible format argument that can be used to specify the conversion needed for your dates. The last example is not in ISO format, but it is in a recognizable format of month, day, year separated by forward slashes. To tell R this, you use a conversion specification. The percent sign followed by m tells R that your date contains a month as a number from 1-12. The forward slashes are the separators between the date pieces. The percent sign followed by d is a day of the month from 1-31. And the percent sign followed by a capital Y is a 4 digit year.

There are a number of conversions available, making the format argument extremely flexible. This table contains some of the most common ones. You can see that the formats are as specific as a two digit year compared to a four digit year. To see an extensive list, visit the help page for strptime. One unique conversion is to use the letter B when your date contains a month name. Let's do one more example with that.

Here you need to convert "September 15, 2008" to a date in R. In case you are curious, this is the date that the company Lehman Brothers filed bankruptcy, the largest bankruptcy filing in United States history. Using the table, you can see that you will need a capital B for September, a lowercase d for 15, and a capital Y for 2008. Also note that you need a comma as a separator after the day. Putting this together, you get the format shown. The spaces in the format are unnecessary, but they allow you to read off the date exactly as it was shown originally.

In addition to creating dates, there are also a few functions for extracting information from a date. One of these is weekdays(). Given a vector of dates, you can extract the day of the week for each date by passing it into weekdays(). In the exercises, you will explore some of the other useful extractor functions.

Time to go explore date formats yourself. Good luck!

#DataCamp #RTutorial #Finance

Комментарии

Информация по комментариям в разработке