Extract Year from Date in R (Example)
This tutorial illustrates how to return only the year of an object with class Date in the R programming language.
The content of the tutorial is structured as follows:
Let’s dive right in:
Creation of Exemplifying Data
Consider the following example data:
my_date <- "2021/01/30" # Create example data my_date # Print example data # "2021/01/30"
As you can see based on the previous output of the RStudio console, our exemplifying data is a single date formatted as character string.
Example: Extracting Only Year from Date Object Using format Function
The following R code illustrates how to extract the year from a date object in R. For this, we first have to convert our character string to the Date class:
my_date_formatted <- as.Date(my_date, format = "%Y/%m/%d") # Convert to Date object my_date_formatted # Print Date object # "2021-01-30"
Let’s check the class of our new data object:
class(my_date_formatted) # Check class # "Date"
Our formatted data object has the class Date. Looks good!
Now, we can apply the format function to extract only the year from our Date object:
my_date_year <- format(my_date_formatted, "%Y") # Extract only year my_date_year # Print final output # "2021"
The output is the year 2021!
Video & Further Resources
I have recently released a video on my YouTube channel, which shows the R codes of this post. You can find the video below:
The YouTube video will be added soon.
Besides the video, I can recommend to have a look at the other tutorials on my website.
- Extract Day from Date in R
- as.Date Function in R
- Convert Date to Numeric Time Object
- Number of Months Between Two Dates
- Extract Year & Month from yearmon Object (zoo Package)
- R Programming Tutorials
In this R post you learned how to extract years from dates. If you have any additional questions, let me know in the comments section below.
Statistics Globe Newsletter