Date formats and extractor functions

Intermediate R for Finance

Lore Dirick

Manager of Data Science Curriculum at Flatiron School

Date formats

# ISO 8601 Standard: year-month-day
as.Date("2017-01-28")
"2017-01-28"
# Alternative form: year/month/day
as.Date("2017/01/28")
"2017-01-28"
# Fails: month/day/year
as.Date("01/28/2017")
Error in charToDate(x) : 
  character string is not in 
  a standard unambiguous format
# Explicitly tell R the format
as.Date("01/28/2017", format = "%m/%d/%Y")
"2017-01-28"
Intermediate R for Finance

Date formats

Format Description
%d Day of the month (01-31)
%m Month (01-12)
%y Year without century (00-99)
%Y Year with century (0-9999)
%b Abbreviated month name
%B Full month name
/ - , Common separators
Intermediate R for Finance

Date formats

Format Description
%d Day of the month (01-31)
%m Month (01-12)
%y Year without century (00-99)
%Y Year with century (0-9999)
%b Abbreviated month name
%B Full month name
/ - , Common separators
Intermediate R for Finance

Date formats

Format Description
%d Day of the month (01-31)
%m Month (01-12)
%y Year without century (00-99)
%Y Year with century (0-9999)
%b Abbreviated month name
%B Full month name
/ - , Common separators
Intermediate R for Finance

Date formats

Format Description
%d Day of the month (01-31)
%m Month (01-12)
%y Year without century (00-99)
%Y Year with century (0-9999)
%b Abbreviated month name
%B Full month name
/ - , Common separators
Intermediate R for Finance

Date formats

Format Description
%d Day of the month (01-31)
%m Month (01-12)
%y Year without century (00-99)
%Y Year with century (0-9999)
%b Abbreviated month name
%B Full month name
/ - , Common separators
Intermediate R for Finance

Date format example

Format Description
%d Day of the month (01-31)
%Y Year with century (0-9999)
%B Full month name
/ - , Common separators
# Lehman Brothers bankruptcy
# Complex format - what do we use?
as.Date("September 15, 2008", format = "___")
as.Date("September 15, 2008", format = "%B %d, %Y")
"2008-09-15"
Intermediate R for Finance

Extractor functions

dates <- as.Date(c("2017-01-03", "2017-01-04"))
weekdays(dates)
"Tuesday"   "Wednesday"
Intermediate R for Finance

Let's practice!

Intermediate R for Finance

Preparing Video For Download...