Aan de slagGa gratis aan de slag

From char to date

You will often have to create dates yourself from character strings. The as.Date() function is the best way to do this:

# The Great Crash of 1929
great_crash <- as.Date("1929-11-29")

great_crash
[1] "1929-11-29"

class(great_crash)
[1] "Date"

Notice that the date is given in the format of "yyyy-mm-dd". This is known as ISO format (ISO = International Organization for Standardization), and is the way R accepts and displays dates.

Internally, dates are stored as the number of days since January 1, 1970, and datetimes are stored as the number of seconds since then. You will confirm this in the exercises below.

Deze oefening maakt deel uit van de cursus

Intermediate R for Finance

Cursus bekijken

Oefeninstructies

  • Create a date variable named crash for "2008-09-29", the date of the largest stock market point drop in a single day.
  • Print crash.
  • Use as.numeric() on crash to convert it to the number of days since January 1, 1970.
  • Wrap as.numeric() around Sys.time() to see the current time in number of seconds since January 1, 1970.
  • Attempt to create a date from "09/29/2008". What happens?

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

# Create crash
crash <- ___

# Print crash
___

# crash as a numeric
___

# Current time as a numeric
___

# Incorrect date format
___
Code bewerken en uitvoeren