2

I have a variable that represents the week of the year (1-53) and I'd like to create new week variables by both adding to and subtracting weeks from it in a way that makes sense given a calendar year.

If I use week + 4, and week = 52, I get week_plus_four = 56; similarly, if I use week - 4, and week = 2, I'd get week_minus_four = - 2. This makes sense, but I'm wondering if there is a function in lubridate or another package that allows you to add and subtract weeks more intuitively.

I know that I could create a function that "wraps around" Dec-Jan, but I wanted to see if there's an existing function that I might have missed in reading through the package notes.

Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
c. garrett
  • 69
  • 2
  • 4
  • A bit of example code would have made this into a much better question. – Mike Wise Jan 20 '16 at 19:41
  • 6
    `lubridate::week(as.Date('2000-01-01') - lubridate::weeks(4))` ? – rawr Jan 20 '16 at 19:44
  • @rawr is there a way to use this logic if I've already saved the 'week(as.Date('2000-01-01')' part as a variable 'my_week'? I can't seem to call a lubridate function on it ("Error: 'my_week' is not an exported object from 'namespace: lubridate'") – c. garrett Jan 20 '16 at 19:50
  • @c.garrett can you add what you just tried to your question with some data, I don't follow when you say "as a part of a variable." `week` should return an integer and then what do you do with that? – rawr Jan 20 '16 at 19:53
  • @rawr I have a variable in a dataframe called my_week with integer values from 1-53. When I do 'lubridate::df$my_week - lubridate::weeks(4)' , I get the error mentioned above. – c. garrett Jan 20 '16 at 19:55
  • think you should keep `df$my_week` as a date object, subtract, _then_ get the `week`. is that what you want? – rawr Jan 20 '16 at 19:59
  • @rawr This works. I got caught up because I wasn't realizing how week was calculated (calendar week vs. number of 7 day periods from Jan 1), but it makes sense now. Thank you! – c. garrett Jan 20 '16 at 22:33

1 Answers1

0

Not quite what you're looking for, but if you wanted to manipulate the dates directly you use %m+% to add a variety of different date parts:

your_date %m+% weeks(1) #adds a week
your_date %m-% weeks(1) #subtracts a week

So if you're applying this to a list of weeks I think in theory you could go:

week(your_dates) %m+% weeks(3)

If that works for you?


Using the same function for months or years:

your_date %m+% months(1) #adds a month
your_date %m+% years(1) #adds a year
your_date %m+% days(1) #adds a day, same as default your_date + 1