Date

"Date" is a special data class for date values in R. Strictly saying, Date is not an R Type, but a class. A class is an attribute assigned to an object regardless of its internal storage structure. To see this, execute the following code

x <- as.Date("2022-11-03")
class(x)  # "Date"
typeof(x) # "double"
  • The only correct date format: YYYY-MM-DD

Conversion to Date

  • Use as.Date(x) to convert to Date class
    • You need to specify the format of x if it is not in YYYY-MM-DD
      • as.Date("1/12/2019", format="%m/%d/%Y")
      • Pay attention to the format: wrong format may give the wrong date
        • as.Date("1/12/2019", format="%m/%d/%y") gives "2020-01-12" because %y is for a two-digit year, and is replaced by 20 here
      • See Conversion Specification for the conversion specification reference
  • A similar function: reader::parse_date
    • parse_date will return NA for parse_date("1/12/2019", format="%m/%d/%y")
  • Use package lubridate

Conversion Specification

Conversion specificationDescriptionExample
%AFull weekdaySunday, Thursday
%b or %hAbbreviated monthMay, Jul
%BFull monthMay, July
%dDay of the month (01-31)27, 07
%jDay of the year (001-366)148, 188
%mMonth (01-12)05, 07
%UWeek (01-53) with Sunday as the first day of the week22, 27
%wWeekday (0-6) with Sunday as 00, 4
%WWeek (00-53) with Monday as the first day of the week21, 27
%xDate, locale-specific
%yYear without century (00-99)84, 05
%YYear with century1984, 2005
%CCentury19, 20
%DDate formatted %m/%d/%y05/27/84, 07/07/05
%uWeekday (1-7) Monday is 17, 4
%nNewline on output or arbitrary whitespace on input
%tTab on output or arbitrary whitespace on input
  • See ?strptime for the reference inside R.

Date Operation

Date class supports the following operations

# Subtraction
as.Date("2022-11-01") - as.Date("2020-11-01")
# Time difference of 730 days 
 
# Addition
as.Date("2022-11-01") + 7
# "2022-11-08"
 
# Comparison
as.Date("2022-11-01") < as.Date("2020-11-01")
# False

scale_x_date

Since dates can be calculated and compared, it is easy to specify the limits and breaks in ggplot2.

  • base + sacle_x_date(limits = c(ymd("2022-01-01"), ymd("2022-11-03")))
  • base + sacle_x_date(limits = c(Sys.Date() - 19, NA))
  • base + sacle_x_date(breaks = "1 week"))
  • base + scale_x_date(date_labels = "%b %d")

Other Functions

  • Sys.date() returns today’s date
  • weekdays(), months(), and quarters() return the weekday, month, and quarter of the date respectively