Create a 52 Week Vector of Dates in R

If you want to keep a weekly log of anything from your body weight to your company’s product sales, it might be easier to have a column of all the dates you’ll need over the next year as a template. That way, when you reach the time each week that you enter your data (say, Monday morning), you can enter the data beside a date that is already there in the adjacent column.

Here’s how to create a vector of weekly dates spanning out over an entire year.

### initialize vector as today's date; if you want to start with a different date, use as.Date("YYYY-MM-DD") in place of Sys.Date() in the code
week_ending = Sys.Date()

### write a for loop on a sequence of next 52 weeks
for(i in seq(from = 1, by = 7, length.out = 52)) {
week_ending[i] = (week_ending - 1) + i
}

### remove NAs from the vector that is created
week_ending = week_ending[!is.na(week_ending)]

### print week_ending to generate a vector of the next 52 weeks, beginning with today's date
week_ending

That’s it. You now have a vector with the length of 52, containing dates for every week over the next year beginning with today. See the code and R output below.

R Output for Vector of Weeks

Feel free to grab this code if it’s useful, and please fix it if there’s a better way!

Advertisements