๐ŸŽ“ A1Learner
๐Ÿ”
0 of 33 lessons completed

R Dates

A date value holds one calendar day. as.Date builds a date value from text in a standard layout.

Reading a date

as.Date reads the text as a date in the year-month-day layout. The date prints with quotes around it.

d <- as.Date("2024-01-31")
print(d)

Adding days to a date

Adding 30 moves the date forward by 30 days. Taking 1 away moves it back by one day.

d <- as.Date("2024-01-31")
print(d + 30)
print(d - 1)

Days between two dates

One date subtracted from a later date gives the gap. The print names the gap as a time difference of 30 days.

start <- as.Date("2024-01-31")
end <- as.Date("2024-03-01")
print(end - start)

Comparing dates

The start date sits before the end date, so the first test gives TRUE. The start date equals its own value, so the second test also gives TRUE.

start <- as.Date("2024-01-31")
end <- as.Date("2024-03-01")
print(start < end)
print(start == as.Date("2024-01-31"))

An impossible date fails

February never holds 31 days in any year. as.Date stops with an error for this text.

print(as.Date("2024-02-31"))

Example

visits <- seq(as.Date("2024-01-15"), by = "month", length.out = 3)
print(visits)
print(visits[3] - visits[1])

Key points

  • as.Date reads text in the year-month-day layout.
  • A date prints with quotes, like a piece of text.
  • Adding a number to a date moves it forward by that many days.
  • Subtracting one date from another gives the days between them.
  • The result of a date subtraction prints as a time difference.
  • Dates compare with the same symbols as numbers.
  • seq builds a run of dates when its start value is a date.

In this example seq starts from a date and steps by one month three times. The last print subtracts the first visit from the third and shows a gap of 60 days.

Note

The year 2024 is a leap year, so February holds 29 days.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท rdrr.io R Snippets

Exercise

What does print(as.Date("2024-01-31") + 30) show?