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 a 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:
Furthermore, I can recommend reading some of the other articles of this homepage.
- Extract Day from Date in R
- Extract Year from Date in R
- Extract Year & Month from yearmon Object (zoo Package)
- as.Date Function in R
- R Programming Overview
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.