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?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With