[R] get start and end date of ISO weeks giving a date as input

Enrico Schumann es at enricoschumann.net
Thu Sep 8 12:53:12 CEST 2016


On Thu, 08 Sep 2016, Veronica Andreo <veroandreo at gmail.com> writes:

> Hello list,
>
> Is there a quick way to get start and end date (%Y-%m-%d) from ISO
> weeks if I only have dates?
>
> For example, I have this date in which some event happened:
> "2010-08-21". Not only I want the ISO week, which I can obtain either
> with isoweek (lubridate) or ISOweek (ISOweek), but I want the start
> and end date of that ISO week.
>
> Do I need to print all ISO weeks from the period of interest and
> sample there for start and end date? Or is there a better way to do
> that?
>
> Thanks a lot in advance!
>
> Best,
> Veronica


You could use a function like the following one (which
assumes the start of the week is Monday and its end is
Sunday):

  d <- c("2010-08-21",
         "2016-08-01")

  iso_start_end <- function(d) {
      d <- as.Date(d)
      wday <- as.POSIXlt(d)$wday
      data.frame(date = d,
                 week = format(d, "%V"),
                 starts = d - wday + 1,
                 ends = d + 7 - wday)
  }
  
  iso_start_end(d)

The function should produce this output:

        date week     starts       ends
1 2010-08-21   33 2010-08-16 2010-08-22
2 2016-08-01   31 2016-08-01 2016-08-07



-- 
Enrico Schumann
Lucerne, Switzerland
http://enricoschumann.net



More information about the R-help mailing list