Dates

Dates are a special type of data in R, and are distinct from the date types POSIXct and POSIXlt, which represent calendar dates and times in more formal ways.

Let's create and check the class() and typeof() of different date objects in R. Follow these steps:

  1. Create the objects using the following code:
e <- as.Date("2016-09-05")
f <- as.POSIXct("2018-04-05")
  1. Check the class and type of each by using class() and typeof(), respectively, as follows:
class(e)
typeof(e)

class(f)
typeof(f)

Output: The preceding code provides the following output:

One nice thing about R is that we can change objects from one type to another using the as.*() function family. If we have a variable, var, which currently has the value of 5, but as a character string, we can cast it to numeric data type using as.numeric() and to an integer using as.integer(), which the following code demonstrates:

#char to numeric, integer
var <- "5"

var_num <- as.numeric(var)
class(var_num)
typeof(var_num)

var_int <- as.integer(var)
class(var_int)
typeof(var_int).

Conversely, we can go the other way and cast the var_num and var_int variables back to the character data type using as.character(). The following code demonstrates this:

#numeric, integer to char
var <- 5

#numeric to char
var_char <- as.character(var_num)
class(var_char)
typeof(var_char)

#int to char
var_char2 <- as.character(var_int)
class(var_char2)
typeof(var_char2)

A character string can be converted into a Date, but it does need to be in the format Year-Month-Day (Y-M-D) so that you can use the as.Date() function, as shown in the following code:

#char to date
date <- "18-03-29"
Date <- as.Date(date)
class(Date)
typeof(Date)

There are formatting requirements for dates for them to save correctly. For example, the following code will not work:

date2 <- as.Date("03-29-18")

It will throw the following error:

Error in charToDate(x) : character string is not in a standard unambiguous format

It will be important to understand variable types throughout a data science project. It would be very difficult to both clean and summarize data if you're unsure of its type. In Chapter 3, Data Management, we'll also introduce another variable type: factors.