My goal is to find the date on a day later in the week based on the information I already have which is another date earlier in the week. In this instance I have a date of 2025-02-16 which I can use weekdays() to work out is a Monday. I now want to find dates for all other days in the week Monday to Sunday, ideally returning the days and dates in a data frame for onward use (this part isn't essential).
theDate = "2025-02-17"
theDay = "Monday"
My initial though was to do this in a while loop like so, although this works I feel like there are better ways to do what I need as I would have to repeat this a few times.
while(weekdays(as.Date(theDate))!="Sunday"){
myDate = theDate+1
}
My end goal is something along the lines of;
datesdf
Monday Tuesday Wednesday Thursday Friday Saturday Sunday
2025-02-16 2025-02-17 2025-02-18 2025-02-19 2025-02-20 2025-02-21 2025-02-22
lubridate
's floor and ceiling functions for dates will help with this:
library(lubridate)
full_week = function(day) {
seq.Date(
from = floor_date(day, unit = "week"),
to = ceiling_date(day, unit = "week", change_on_boundary = FALSE),
by = "day"
)
}
theDate = "2025-02-17"
full_week(ymd(theDate))
# [1] "2025-02-16" "2025-02-17" "2025-02-18" "2025-02-19" "2025-02-20" "2025-02-21" "2025-02-22"
That should be enough to get you started - if you want to put the resulting vector dates in a data frame and name the columns with the day names, I'll leave that to you.