-1

I'd like to get week number in year which starts on Friday in R. For example:

2016-01-01 to 2016-01-07 is 1st week of the year

2016-01-08 to 2016-01-14 is 2nd week of the year

Can you help?

Taz
  • 5,755
  • 6
  • 26
  • 63

2 Answers2

-1

One package you might find useful is Lubridate. It really helps with tasks using dates and times.

For example:

> library(lubridate)
> week(as.POSIXct("2016-01-01"))
[1] 1

Or, if you are curious about what week number Halloween falls on:

> week(as.Date("2016-10-31"))
[1] 44

for more info: https://cran.r-project.org/web/packages/lubridate/lubridate.pdf

Ryan Pugh
  • 243
  • 2
  • 9
  • I know this but it is not the solution, beacuse I can't choose when week starts/ends. – Taz Jan 05 '16 at 17:50
-1

You can use lubridate in this case, I've just had the same problem as you are. In my case I need it to be started on Wed, so this code below is to start week on Wednesday,

weekOnWed <- function(theDate) {
  formattedDate <- dmy (theDate)
  i <- 1
  while (i <= 7) {
    isWed <- dmy(paste("0", as.character(i), "/01/", year(formattedDate), sep = ""))
    ## because Wed is the 4th day of the week on Lubridate

you need to change the number below to 6 (as Fri is 6th day) on Lubridate

    if (wday(isWed) == 4) {
      break;
    }
    else {
      i <- i + 1
    }
  }
  firstWed <- day(isWed)
  if (firstWed > 1) {
    firstWeek <- 2
  }
  else {
    firstWeek <- 1
  }
  rangeWeek <- as.integer(formattedDate - isWed) %/% 7
  weekNum <- rangeWeek + firstWeek
  weekNum
}

input: string (in dd-mm-yyyy) format

output of this function is week number in integer

hopefully that helps :)

piwpiw
  • 11
  • 1
  • 4