How To Extract Year From Date In R

In this article, we will share some solutions to extract year from date in R. Read the full article to know how to extract year from date in R and choose the best solution for your program. Let’s go.

How to extract year from date in R

There are many ways to extract year from date in R. We cover two popular solutions that use format() function and year() function (in the lubridate package).

Using the format() function

To extract year from date, we use the as.Date() function (you can also use similar functions, for example, the as.POSIXct() function) to create a date object with a specific format. Then we use the format() function to get the year from the newly created date object.

Example:

# Create a date object
date_str <- c("2022/12/25", "2023/01/01")
date <- as.Date(date_str, format = "%Y/%m/%d")

# Extract year from date
format(date, format = "%Y")

Output:

[1] "2022" "2023"

Using the year() function in the ‘lubridate’ package

The year() function (provided by the lubridate package) is used to get or set the year for date objects or strings with a standard unambiguous format.

Syntax to get years component of date-time:

year(x)

Parameters:

x: a date-time object or a date string.

To use the year() function to extract year from date, first, you must install and load the lubridate package:

library('lubridate')

Example:

library('lubridate')
date <- c("2022/12/25", "2023/01/01")

# Extract year from date
year(date)

Output:

[1] 2022 2023

If you enter a date string representing a date object in the dmy or ymd format, the year() function will correctly infer the format itself, as shown in the example above.

If the input string is not in the dmy or ymd format, you must convert it to a date object with a specific format.

Example:

library('lubridate')

# Create a date object
date_str <- c("2022/25/12", "2023/15/01")
date <- as.Date(date_str, format = "%Y/%d/%m")

# Extract year from date
year(date)

Output:

[1] 2022 2023

You can also use the year() function provided by the data.table package with the same usage and results.

Read more how to extract month from date in R here.

Summary

We have shared how to extract year from date in R. You must remember to install and load the lubridate package first if you use the year() function of the lubridate package. If the string passed to the year() function does not have an explicit format, convert it to a date object with a specific format. Thank you for reading.

Posted in R

Leave a Reply

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