Specifying dates
As you saw in the video, R doesn't know something is a date unless you tell it. If you have a character string that represents a date in the ISO 8601 standard you can turn it into a Date using the as.Date() function. Just pass the character string (or a vector of character strings) as the first argument.
In this exercise you'll convert a character string representation of a date to a Date object.
This exercise is part of the course
Working with Dates and Times in R
Exercise instructions
We've stored the string "2013-04-03" in a variable called x.
- Use
str()to look at the structure ofxand confirm it's just a character string. - Convert
xto a date usingas.Date(). - Use
str()to look at the structure ofx_dateand confirm it's aDate. - Now use
as.Date()to store the date April 10, 2014.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# The date R 3.0.0 was released
x <- "2013-04-03"
# Examine structure of x
str(___)
# Use as.Date() to interpret x as a date
x_date <- ___
# Examine structure of x_date
str(___)
# Store April 10 2014 as a Date
april_10_2014 <- ___