Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get ISO week numbers from date

Tags:

r

I would like to get the ISO week number from a given date in string format, where Monday is the first day of the week, and the week that contains the first Thursday of the year is considered to be the first week.

From other answers, I think strftime("2017-11-18", format = "%V") suits my purpose the best. However it doesn't work on Windows.

Any suggestions for alternatives with only the base package in R?

like image 761
noname Avatar asked Oct 19 '25 12:10

noname


1 Answers

Use the package lubridate

it has a function isoweek()which gives you the ISOWeek of a given date

lubridate::isoweek("2017-11-18")
[1] 46

Now you just want to use the base packege. Here ist the code from lubridate for the ISO week

function (x) 
{
  xday <- make_datetime(year(x), month(x), day(x))
  dn <- 1 + (wday(x) + 5)%%7
  nth <- xday + ddays(4 - dn)
  jan1 <- make_datetime(year(nth), 1, 1)
  1L + as.integer(difftime(nth, jan1, units = "days"))%/%7L
}

we can take that an make it to something which only uses the base package.

myIsoweek <- function (x) 
{
  dateList <- as.list(strsplit(as.character(as.Date(x)),split = "-")[[1]])
  names(dateList) <- c("year","month","day")

  weekday <- as.POSIXlt(x)[["wday"]] + 1

  xday <- ISOdate(dateList$year, dateList$month, dateList$day)
  dn <- 1 + (weekday + 5)%%7
  nth <- xday + 86400*(4 - dn)
  jan1 <- ISOdate(format(nth,format = "%Y"), 1, 1)
  1L + as.integer(difftime(nth, jan1, units = "days"))%/%7L
}
like image 146
Bertil Baron Avatar answered Oct 22 '25 03:10

Bertil Baron