Prakhar Mehrotra
Prakhar Mehrotra

Reputation: 1231

How to calculate date based on week number in 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

Upvotes: 7

Views: 6707

Answers (4)

Datoraki
Datoraki

Reputation: 1223

You can also use strptime to easily get dates from weeks starting on Mondays:

first_date_of_week <- function(year, week){
  strptime(paste(year, week, 1), format = "%Y %W %u")
}

Upvotes: 2

Fabio
Fabio

Reputation: 518

You can accomplish this using the package lubridate

library(lubridate)
start = ymd("2014-01-01")
#[1] "2014-01-01 UTC"

end = start+10*weeks()
end = end-(wday(end)-1)*days()
#[1] "2014-03-09 UTC"

Upvotes: 1

Henrik
Henrik

Reputation: 67828

You may try the ISOweek2date function in package ISOweek.

Create a function which takes year, week, weekday as arguments and returns date(s):

date_in_week <- function(year, week, weekday){
  w <- paste0(year, "-W", sprintf("%02d", week), "-", weekday)
  ISOweek2date(w)
}

date_in_week(year = 2014, week = 10, weekday = 1)
# [1] "2014-03-03"

This date is corresponds to an ISO8601 calendar (see %V in ?strptime). I assume you are using the US convention (see %U in ?strptime). Then some tweeking is needed to convert between ISO8601 and US standard:

date_in_week(year = 2014, week = 10 + 1, weekday = 1) - 1
# [1] "2014-03-09"

You can enter several weekdays, e.g.

date_in_week(year = 2014, week = 10 + 1, weekday = 1:3) - 1
# [1] "2014-03-09" "2014-03-10" "2014-03-11"

Upvotes: 7

BrodieG
BrodieG

Reputation: 52697

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.

Upvotes: 7

Related Questions