ISO week number and ISO year in R

ISO week number and ISO year in R

The easiest way to do ISO week number and ISO year calculations in R is by using two simple functions from package lubridate.

It is also possible to do those calculations by using the main principles of ISO week numbering from Wikipedia as I did in Power Query.

Luckily for R users, there is a very useful lubridate package that comes with functions isoweek and isoyear. Sometimes it is very useful to use ISO week and ISO year calculations together to avoid incorrect grouping.

To test how it works it is useful to generate a date sequence like this. Before that – an interesting approach on how to create an empty R data frame.

x <- NULL

x$date <- seq.Date(from = as.Date('2020-12-25'), to = as.Date('2021-01-05'), by = 'days')

x <- data.frame(x)

x
#         date
#1  2020-12-25
#2  2020-12-26
#3  2020-12-27
#4  2020-12-28
#5  2020-12-29
#6  2020-12-30
#7  2020-12-31
#8  2021-01-01
#9  2021-01-02
#10 2021-01-03
#11 2021-01-04
#12 2021-01-05

Here come the ISO week number and ISO year in R

x$iso_week_num <- lubridate::isoweek(x$date)

x$iso_year <- lubridate::isoyear(x$date)

x
#         date iso_week_num iso_year
#1  2020-12-25           52     2020
#2  2020-12-26           52     2020
#3  2020-12-27           52     2020
#4  2020-12-28           53     2020
#5  2020-12-29           53     2020
#6  2020-12-30           53     2020
#7  2020-12-31           53     2020
#8  2021-01-01           53     2020
#9  2021-01-02           53     2020
#10 2021-01-03           53     2020
#11 2021-01-04            1     2021
#12 2021-01-05            1     2021

I’m personally not a big fan of using week number dimensions but if it is necessary then it’s better with ISO week number. At least there will be 7 days in every week and more objective comparison.

What’s next?

Take a look at my favorite RStudio tips and tricks. For example, how to fold a part of the R code and use section naming or how to comment out multiple lines of R script at once.





Posted

in

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *