# Create a date object
date <- as.Date("2024-01-31")
# Add 5 days to the date
new_date <- date + 5
print(date)[1] "2024-01-31"
print(new_date)[1] "2024-02-05"
class(date)[1] "Date"
class(new_date)[1] "Date"
Steven P. Sanderson II, MPH
January 31, 2024
Ever wished you could skip ahead a few days for that weekend getaway, or rewind to relive a magical moment? While real-life time travel remains a sci-fi dream, in R, adding days to dates is a breeze! Today, we’ll explore both base R and the powerful lubridate and timetk packages to master this handy skill.
Let’s start with the classic. Imagine you have a date stored as my_date <- "2024-01-31" (yes, today!). To add, say, 5 days, you can simply use my_date + 5. Voila! You’ve time-jumped to February 5th, 2024. But wait, this doesn’t handle months or leap years like a pro.
lubridateThis superhero package offers functions like as.Date() and days() that understand the nuances of dates. Let’s revisit our example:
library(lubridate)
my_date <- as.Date("2024-01-31") # Convert string to Date object
future_date <- my_date + days(5) # Add 5 days using days()
future_date # "2024-02-05"[1] "2024-02-05"
See the magic? days(5) tells R to add 5 days specifically. You can even subtract days (imagine reliving that delicious pizza!):
timetk Takes the WheelWant to add weeks, months, or even years? timetk takes things to the next level with functions like years(), wednesdays(), and more. Check this out:
library(timetk)
graduation <- as.Date("2025-06-15") # Your graduation date (hopefully!)
graduation %+time% "1 hour 34 seconds"[1] "2025-06-15 01:00:34 UTC"
[1] "2025-09-15"
[1] "2026-09-21"
[1] "2025-06-14 22:59:26 UTC"
[1] "2025-03-15"
[1] "2024-03-09"
Bonus Tip: Don’t forget about formatting! Use format() with options like "%Y-%m-%d" to display your dates in your preferred format.
Remember, practice makes perfect. The more you play with dates in R, the more comfortable you’ll become with this essential skill. So go forth, explore, and conquer the realm of time in R!
P.S. Share your coolest date-manipulation tricks in the comments below. Let’s learn from each other and keep the R community thriving!