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'
-
2sounds like a cool function. what do you have? – rawr Jan 16 '16 at 02:22
-
3http://stackoverflow.com/questions/28971638/r-obtaining-last-fridays-date – hrbrmstr Jan 16 '16 at 02:31
-
2`PrevMon <- function(x){ x <- as.POSIXlt(x, format = "%m/%d/%Y") x$mday <- x$mday - ((x$wday - 1) %% 7) - 7 return(x) }` – Chris Jan 16 '16 at 02:36
-
thanks guys! Chris's solution works well. – Steve Palley Jan 16 '16 at 02:51
2 Answers
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.

- 1
- 1

- 254,981
- 17
- 203
- 341
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)

- 131
- 8