# Simplifying Date Manipulation: How to Get Week Numbers in R

code
rtip
timeseries
Author

Steven P. Sanderson II, MPH

Published

February 6, 2024

# Introduction

When working with dates in R, you may need to extract the week number for any given date. This can be useful for doing time series analysis or visualizations by week.

In this post, I’ll demonstrate how to get the week number from dates in R using both base R and the lubridate package. I’ll provide simple examples so you can try it yourself.

## Using Base R

In base R, the `strftime()` function is used to format dates and extract different date components like day, month, year etc.

The syntax for `strftime()` is:

``strftime(x, format, tz = "")``

Where:

• `x`: is the date object
• `format`: is the format string specifying which date components to extract
• `tz`: is an optional time zone string

To get the week number, we need to use `"%V"` in the format string. This tells `strftime()` to return the ISO 8601 standard week number.

Let’s see an example:

``````date <- as.Date("2023-01-15")

strftime(date, format = "%V") ``````
``[1] "02"``

This returns the week number as a string. In this case, it’s the second week of the year.

We passed the date object to `strftime()` along with the format string containing `"%V"`.

Let’s try another example on a vector of dates:

``````dates <- as.Date(c("2023-01-15", "2023-02-28", "2023-12-31"))

strftime(dates, format = "%V")``````
``[1] "02" "09" "52"``

This returns the week number for each date. So with base R, we can use `strftime()` and `%V` to easily extract week numbers from dates.

## Using lubridate

The lubridate package provides a wrapper function called `week()` to get the week number from a date.

The syntax for `week()` is simple:

``week(x)``

Where x is the date object.

Let’s see an example:

``````library(lubridate)

date <- ymd("2023-01-15")

week(date)``````
``[1] 3``

This returns a numeric value representing the week number. In this case, it’s the third week of the year.

For a vector of dates:

``````dates <- ymd(c("2023-01-15", "2023-02-28", "2023-12-31"))

week(dates) ``````
``[1]  3  9 53``

So `week()` makes it easy to extract the week number from dates in lubridate. You will also notice that `strftime()` returns “52” for the last date of the year, while `week()` returns “53”. This is because `week()` follows the ISO 8601 standard for week numbers.

## Wrap Up

To quickly recap the key points:

• Base R: `strftime(date, format = "%V")`
• lubridate: `week(date)`

I encourage you to try these functions out on some sample dates in R. Being able to wrangle dates is an important skill for handling temporal data.

Let me know if you have any other questions!