[R] getting ISO week

Gustaf Rydevik gustaf.rydevik at gmail.com
Thu Dec 11 13:43:37 CET 2008


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



More information about the R-help mailing list