An introduction to dates in R Lore Dirick Instructor, DataCamp - - PowerPoint PPT Presentation

an introduction to dates in r
SMART_READER_LITE
LIVE PREVIEW

An introduction to dates in R Lore Dirick Instructor, DataCamp - - PowerPoint PPT Presentation

INTERMEDIATE R FOR FINANCE An introduction to dates in R Lore Dirick Instructor, DataCamp Intermediate R for Finance What will you learn? If statements Loops Functions Finance examples Intermediate R for Finance


slide-1
SLIDE 1

INTERMEDIATE R FOR FINANCE

An introduction to dates in R

Lore Dirick

Instructor, DataCamp

slide-2
SLIDE 2

Intermediate R for Finance

What will you learn?

  • If statements
  • Loops
  • Functions
  • Finance examples
slide-3
SLIDE 3

Intermediate R for Finance

Today's date

> today <- Sys.Date() > today [1] "2017-03-14" > class(today) [1] "Date"

slide-4
SLIDE 4

Intermediate R for Finance

Date classes

  • Date
  • Calendar dates
  • "2017-03-14"
  • POSIX - Portable Operating System Interface
  • POSIXct and POSIXlt
  • Date + time + timezone
  • "2017-03-14 10:00:21 EDT"
slide-5
SLIDE 5

Intermediate R for Finance

Creating dates

> character_date <- "1957-03-04" > class(character_date) [1] "character" > sp500_birthday <- as.Date(character_date) > sp500_birthday [1] "1957-03-04" > class(sp500_birthday) [1] "Date"

slide-6
SLIDE 6

INTERMEDIATE R FOR FINANCE

Let’s practice!

slide-7
SLIDE 7

INTERMEDIATE R FOR FINANCE

Date formats and extractor functions

slide-8
SLIDE 8

Intermediate R for Finance

Date formats

> # ISO 8601 Standard: year-month-day > as.Date("2017-01-28") [1] "2017-01-28" > # Alternative form: year/month/day > as.Date("2017/01/28") [1] "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") [1] "2017-01-28"

slide-9
SLIDE 9

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

slide-10
SLIDE 10

Intermediate R for Finance

Date format example

> # Lehman Brothers bankruptcy > # Complex format - what do we use? > as.Date("September 15, 2008", format = "___")

Format Description %d Day of the month (01-31) %Y Year with century (0-9999) %B Full month name "/" "-" "," Common separators

> as.Date("September 15, 2008", format = "%B %d, %Y") [1] "2008-09-15"

slide-11
SLIDE 11

Intermediate R for Finance

Extractor functions

> dates <- as.Date(c("2017-01-03", "2017-01-04")) > weekdays(dates) [1] "Tuesday" "Wednesday"

slide-12
SLIDE 12

INTERMEDIATE R FOR FINANCE

Let’s practice!