Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate date based on week number in R

Tags:

r

I was wondering if there is a way to get the begin of the week date based on a week number in R? For example, if I enter week number = 10, it should give me 9th March, 2014.

I know how to get the reverse (aka..given a date, get the week number by using as.POSIX functions).

Thanks! Prakhar

like image 405
Prakhar Mehrotra Avatar asked Mar 19 '14 21:03

Prakhar Mehrotra


1 Answers

You can try this:

first.day <- as.numeric(format(as.Date("2014-01-01"), "%w"))
week <- 10
as.Date("2014-01-01") + week * 7 - first.day
# [1] "2014-03-09"

This assumes weeks start on Sundays. First, find what day of the week Jan 1 is, then, just add 7 * number of weeks to Jan 1, - the day of week Jan 1 is.

Note this is slightly different to what you get if you use %W when doing the reverse, as from that perspective the first day of the week seems to be Monday:

format(seq(as.Date("2014-03-08"), by="1 day", len=5), "%W %A %m-%d")
# [1] "09 Saturday 03-08"  "09 Sunday 03-09"    "10 Monday 03-10"    "10 Tuesday 03-11"  
# [5] "10 Wednesday 03-12"

but you can adjust the above code easily if you prefer the Monday centric view.

like image 63
BrodieG Avatar answered Sep 20 '22 03:09

BrodieG