4

I'm looking for a way to find the date object for the PREVIOUS calendar week's Monday. For example, today is 1/15/2016; I need to build a function that will return '2016-01-04 UTC'

Steve Palley
  • 325
  • 1
  • 3
  • 11

2 Answers2

8

The question asks for the "previous calendar week's Monday". We assume below that this means that you want the Monday on or before the input date.

Note that it would be better to use "Date" class since times are not needed and "Date" class has no time zone so it avoids potential time zone errors associated with "POSIXt" classes.

There is nextfri function in the zoo vignette, zoo quickref vignette which we can use as the basis of a similar function. We make these changes (1) ceiling is replaced with floor, (2) 5 (Friday) is replaced with 1 (Monday) and (3) we add the origin= argument to as.Date -- if zoo is loaded a default origin is provided so the origin= argument could be optionally omitted.

This function uses only base R and is vectorized. It accepts a "Date" class vector and returns a "Date" class vector of dates for the Monday on or before the respective input dates.

lastmon <- function(x) 7 * floor(as.numeric(x-1+4)/7) + as.Date(1-4, origin="1970-01-01")

For example,

 > lastmon(as.Date(c("2016-01-15", "2016-01-11")))
[1] "2016-01-11" "2016-01-11"

The lastmon function could alternately be simplified to just:

lastmon2 <- function(x) x - as.numeric(x-1+4)%%7

Note: also see the SO answers here, here, here and here for more uses of nextfri or variations thereof.

Community
  • 1
  • 1
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
2

There's also a lubridate solution (from martin.R):

library(lubridate)
ceiling_date(your_date, "week", 1)

Likewise, to find last Monday:

floor_date(your_date, "week", 1)

Documentation of the functions.