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"

Conversion to Date

Conversion Specification

Conversion specification Description Example
%A Full weekday Sunday, Thursday
%b or %h Abbreviated month May, Jul
%B Full month May, July
%d Day of the month (01-31) 27, 07
%j Day of the year (001-366) 148, 188
%m Month (01-12) 05, 07
%U Week (01-53) with Sunday as the first day of the week 22, 27
%w Weekday (0-6) with Sunday as 0 0, 4
%W Week (00-53) with Monday as the first day of the week 21, 27
%x Date, locale-specific
%y Year without century (00-99) 84, 05
%Y Year with century 1984, 2005
%C Century 19, 20
%D Date formatted %m/%d/%y 05/27/84, 07/07/05
%u Weekday (1-7) Monday is 1 7, 4
%n Newline on output or arbitrary whitespace on input
%t Tab on output or arbitrary whitespace on input

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.

Other Functions

Creative Commons License by zcysxy