Get Week Number of Date in R (2 Examples)
In this R programming tutorial you’ll learn how to extract the week number from a date object.
The tutorial consists of these topics:
Let’s take a look at some R codes in action.
Creation of Example Data
In the first place, we’ll need to create some example data:
my_date <- "2022-10-05" # Create example date my_date # Print example date #  "2022-10-05"
As you can see based on the previous output of the RStudio console, our example data is a character string containing a date (i.e. the 5th of October of the year 2022).
Example 1: Get Week Number of Date Using strftime() Function
The following syntax illustrates how to apply the strftime function provided by the basic installation of the R programming language to get the week number of our example date.
Have a look at the following R code:
strftime(my_date, format = "%V") # Apply strftime function #  "40"
The RStudio console returns the result – The week number that corresponds to our example date is the number 40.
Example 2: Get Week Number of Date Using week() & ymd() Functions of lubridate Package
In this example, I’ll illustrate how to use the functions of the lubridate package to return week numbers of date objects.
If we want to use the functions of the lubridate package, we first have to install and load lubridate:
install.packages("lubridate") # Install & load lubridate library("lubridate")
Now, we can apply the week and ymd functions to extract the week number of our date:
lubridate::week(ymd(my_date)) # Apply week & ymd functions #  40
The previous R code returns the week number that we already know from the first example – The week number 40.
Note that it is advisable to add the lubridate package name in front of the week function, since the data.table package also provides a function with the same name.
Video & Further Resources
Have a look at the following video of the Statistics Globe YouTube channel. In the video, I’m explaining the R programming code of this article:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
In addition, you could have a look at the other tutorials on this website.
To summarize: In this R tutorial you have learned how to convert dates to week numbers. Let me know in the comments section, in case you have any further questions.
2 Comments. Leave new
Leave a Reply Cancel reply
Statistics Globe Newsletter
Error in ymd(date_time) : could not find function “ymd”
May i know what went wrong?
I assume there are two possible solutions.
1) Add lubridate:: in front of each function coming from this package:
2) Load lubridate for the entire R session: