[R] getting ISO week

Prof Brian Ripley ripley at stats.ox.ac.uk
Thu Dec 11 14:10:11 CET 2008


A slightly simpler version is

format(Sys.Date(), "%V")


On Thu, 11 Dec 2008, Prof Brian Ripley wrote:

> strftime(x, "%V")
>
> E.g.
>
> strftime(as.POSIXlt(Sys.Date()), "%V")
>
> is "50", and you might want as.numeric() on it.
>
> Note that this is OS-dependent, and AFAIR Windows does not have it.
>
> On Thu, 11 Dec 2008, Gustaf Rydevik wrote:
>
>> Hi all,
>> 
>> Is there a simple function already implemented for getting the ISO
>> weeks of a Date object?
>> I couldn't find one, and so wrote my own function to do it, but would
>> appreciate a pointer to the "default" way. If a function is not yet
>> implemented, could the code below be of interest to submit to CRAN?
>> 
>> Best Regards,
>> 
>> Gustaf
>> 
>> --------------------
>> 
>> getweek<-function(Y,M=NULL,D=NULL){
>>
>>  if(!class(Y)[1]%in%c("Date","POSIXt")) {
>>  date.posix<-strptime(paste(c(Y,M,D),collapse="-"),"%Y-%m-%d")
>>  }
>>  if(class(Y)[1]%in%c("POSIXt","Date")){
>> date.posix<-as.POSIXlt(Y)
>> Y<-as.numeric(format(date.posix,"%Y"))
>> M<-as.numeric(format(date.posix,"%m"))
>> D<-as.numeric(format(date.posix,"%d"))
>>  }
>> 
>>
>>  LY<- (Y%%4==0 & !(Y%%100==0))|(Y%%400==0)
>>  LY.prev<- ((Y-1)%%4==0 & !((Y-1)%%100==0))|((Y-1)%%400==0)
>>  date.yday<-date.posix$yday+1
>>  jan1.wday<-strptime(paste(Y,"01-01",sep="-"),"%Y-%m-%d")$wday
>>  jan1.wday<-ifelse(jan1.wday==0,7,jan1.wday)
>>  date.wday<-date.posix$wday
>>  date.wday<-ifelse(date.wday==0,7,date.wday)
>> 
>>
>>  ####If the date is in the beginning, or end of the year,
>>  ### does it fall into a week of the previous or next year?
>>  Yn<-ifelse(date.yday<=(8-jan1.wday)&jan1.wday>4,Y-1,Y)
>>  Yn<-ifelse(Yn==Y&((365+LY-date.yday)<(4-date.wday)),Y+1,Y)
>>
>>  ##Set the week differently if the date is in the beginning,middle or
>> end of the year
>>
>>  Wn<-ifelse(
>>      Yn==Y-1,
>>      ifelse((jan1.wday==5|(jan1.wday==6 &LY.prev)),53,52),
>>      ifelse(Yn==Y+1,1,(date.yday+(7-date.wday)+(jan1.wday-1))/7-(jan1.wday>4))
>>      )
>>    return(list(Year=Yn,ISOWeek=Wn))
>> }
>> 
>> 
>> -- 
>> Gustaf Rydevik, M.Sci.
>> tel: +46(0)703 051 451
>> address:Essingetorget 40,112 66 Stockholm, SE
>> skype:gustaf_rydevik
>
>
> -- 
> Brian D. Ripley,                  ripley at stats.ox.ac.uk
> Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
> University of Oxford,             Tel:  +44 1865 272861 (self)
> 1 South Parks Road,                     +44 1865 272866 (PA)
> Oxford OX1 3TG, UK                Fax:  +44 1865 272595
>

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-help mailing list