Extract Month from Date in R (Example)

 

In this R post you’ll learn how to return only the months of a date vector.

Table of contents:

Let’s just jump right in:

 

Construction of Example Data

Have a look at the example data below:

x <- "2022-10-05"                                 # Create example date
x                                                 # Print date
# "2022-10-05"

As you can see based on the previous output of the RStudio console, our example data object contains a single date formatted as character string.

 

Example: Extracting Month from Date Object Using as.Date() & format() Functions

This example shows how to extract the month of a date in R. For this, we first have to convert our data object to the Date class using the as.Date function:

x_formatted <- as.Date(x, format = "%Y-%m-%d")    # Convert character to Date
x_formatted                                       # Print Date object
# "2022-10-05"

The formatted data object looks exactly the same as the original data. However, we can see the difference when checking the class:

class(x_formatted)                                # Checking class
# "Date"

Our new data object has the data type Date.

Now, we can use the format function to extract only the month from our object with the data type Date:

x_month <- format(x_formatted, "%m")              # Extract month
x_month                                           # Print month
# 10

The month of our date is October (i.e. the value 10).

 

Video, Further Resources & Summary

I have recently released a video on my YouTube channel, which illustrates the examples of this article. You can find the video below:

 

The YouTube video will be added soon.

 

Furthermore, I can recommend to read some of the other articles of this homepage.

 

In summary: At this point you should know how to get the month from an object with the class Date in R programming. In case you have further questions, tell me about it in the comments section below.

 

Subscribe to my free statistics 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