[R] Assigning week numbers

Gustaf Rydevik gustaf.rydevik at gmail.com
Thu Apr 22 10:07:58 CEST 2010


On Wed, Apr 21, 2010 at 6:50 PM, Michael Hosack <mhosack9 at hotmail.com> wrote:
>
>
> I provided a minimized version of my dataframe at the bottom of this message containing the results of David's code in variable ('wkoffset') and Jeff Hallman's code in ('WEEK'). Jeff's code produced the correct results (thank you Jeff) though I have been unable to understand it. David, as you can see your code begins week 2 for year 2011 on a Wednesday, rather than on a Saturday, as it should. Your adjustment seems not to correct the problem, but I concede I may be using it incorrectly. If you are obtaining the correct results please let me know what I am doing wrong.
>
> Thanks,
>
> Mike
>


Hello again,

Just for fun, I implemented the gist of your original code in R. It's
much longer and not as elegant as the other solutions, but perhaps
someone can learn something from it.
Regards,
Gustaf

------------------------------------

Daterange<-range(SCHEDULE3$DATE.)
Daterange[1]<-paste(as.numeric(
    substr(as.character(Daterange[1]),1,4))-1,
    "-05-01",sep="")
Daterange[2]<-paste(as.numeric(
    substr(as.character(Daterange[2]),1,4))+1,
    "-05-01",sep="")

alldates<-seq(from=Daterange[1],to=Daterange[2],by=1)


My.locale<-Sys.getlocale("LC_TIME")
Sys.setlocale("LC_TIME","English_USA.1252")
Week<-1
allweeks<-vector(length=length(alldates))


for(i in seq_along(alldates)){
    if(weekdays(alldates[i])=="Saturday"){
        Week<-Week+1
    }
    if(substr(as.character(alldates[i]),6,10)=="05-01"){
        Week<-1
    }
    allweeks[i]<-Week
}

SCHEDULE3$Week<-allweeks[match(SCHEDULE3$DATE.,alldates)]

Sys.setlocale("LC_TIME",My.locale)



-- 
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