Reputation: 323
I am trying to get the month number of a date based on some basic addition to other elements in my r function. However, I cannot seem to get the calculation correct as it appears that it is treating the month as a 'number' and not recognizing for instance that '13' is not a valid month. I am very new to r but hoping maybe there is any easy solution.
Here is the line in question:
end_month <- month(last_covered_date) + interval - 1
the variable in question in 'last_covered_date' and it has been converted to a date using as.Date. interval is a number i.e. 1,2,3 and then we are always subtracting 1 from that to get the month we need. It seems to work fine until we start dealing with December - in this case the interval is 2... so it is 12+2 = 14 and minus 1 gets to 13. I need somehow to make it recognize 13 should be '01'...tried pushing a case_when statement in just to get it to work but no luck.
Upvotes: 0
Views: 101
Reputation:
I would use the built-in date math to do date math...
some_date = as.Date("2020-01-01")
one_month_from_some_date = some_date + months(1) # 2020-02-01
one_hundred_months_from_some_date = some_date + months(100) # 2028-05-01
Upvotes: 2