[R] Convert week value to date

Gabor Grothendieck ggrothendieck at gmail.com
Thu Aug 18 18:44:33 CEST 2011


On Wed, Aug 17, 2011 at 4:52 PM, Folkes, Michael
<Michael.Folkes at dfo-mpo.gc.ca> wrote:
> Hello all,
> I'm hoping to convert a decimal value for week of the year back to a date object.
> Eg:
> strptime(paste(2010,1:52,sep=" "),format="%Y %W")
>
> I expected (hoped?) this would give me the date for Monday of each week.  Instead, it's giving me 52 values of today's date.
>

If the objective is to get all the Mondays in 2011 then:

s <- seq(as.Date("2011-01-01"), as.Date("2011-12-31"), by = "day")
s[format(s, "%w") == "1"]

If the objective is to get the previous Monday relative to an input
date (or the same date if its already Monday) then in the zoo-quickref
vignette is a function nextfri which outputs the next Friday on or
after the input date.  We can readily modify that to get the prior
Monday on or before the current date:

prevmonday <- function(x) 7 * floor(as.numeric(x-1+4) / 7) + as.Date(1-4)

For example,

> prevmonday(Sys.Date())
[1] "2011-08-15"
> prevmonday(prevmonday(Sys.Date()))
[1] "2011-08-15"

-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list