<- as.Date("2023-01-15")
date
strftime(date, format = "%V")
[1] "02"
Steven P. Sanderson II, MPH
February 6, 2024
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.
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 objectformat
: is the format string specifying which date components to extracttz
: is an optional time zone stringTo 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:
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:
[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.
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:
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:
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.
To quickly recap the key points:
strftime(date, format = "%V")
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!