r - finding the previous Monday -
i'm looking way find date object previous calendar week's monday. example, today 1/15/2016; need build function return '2016-01-04 utc'
the question asks "previous calendar week's monday". assume below means want monday on or before input date.
note better use "date"
class since times not needed , "date"
class has no time zone avoids potential time zone errors associated "posixt"
classes.
there nextfri
function in zoo vignette, zoo quickref vignette can use basis of similar function. make these changes (1) ceiling
replaced floor
, (2) 5 (friday) replaced 1 (monday) , (3) add origin=
argument to as.date
-- if zoo loaded default origin provided origin=
argument optionally omitted.
this function uses base r , vectorized. accepts "date"
class vector , returns "date"
class vector of dates monday on or before 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 alternately simplified just:
lastmon2 <- function(x) x - as.numeric(x-1+4)%%7
note: see answers here, here, here , here more uses of nextfri
or variations thereof.
Comments
Post a Comment