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
# [1] "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
# [1] "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
# [1] 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:

 

The YouTube video will be added soon.

 

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.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top