How to Get Year from Date in R (3 Easy Ways)
In this article
Extracting the year from a date is one of the most common data-cleaning tasks in R. Whether you're analyzing sales trends, grouping by season, or just formatting a report, you'll often need just the year component from a full date. This guide shows you three straightforward methods using base R and the popular lubridate package. No prior experience with dates in R is needed—just a working R environment and a vector of dates.
What You'll Need
- R installed (version 3.6 or later recommended)
- RStudio (optional but helpful)
- A vector of dates, either as
Dateobjects or character strings - For the
lubridatemethod, install the package withinstall.packages("lubridate")
Step-by-Step
-
Prepare your date data.
Make sure your dates are recognized as dates by R. If they are character strings like "2023-05-14", convert them using
as.Date():dates <- as.Date(c("2023-05-14", "2021-11-02", "2020-01-31"))If your dates are already in
DateorPOSIXctformat, you can skip this step. -
Method 1: Use
format()(base R).The simplest base R approach uses the
format()function with the"%Y"format specifier, which returns the four-digit year:years <- format(dates, "%Y")This returns a character vector. If you need numeric values, wrap it with
as.numeric():years_num <- as.numeric(format(dates, "%Y")) -
Method 2: Use
lubridate::year().The
lubridatepackage provides a cleaner, more intuitive function. First, load the package:library(lubridate)Then simply call
year()on your date vector:years <- year(dates)This returns a numeric vector directly, which is often more convenient for further calculations.
-
Method 3: Use
as.integer()withsubstr()(for character dates).If your dates are stored as strings in the format "YYYY-MM-DD" and you don't want to convert them, you can extract the first four characters:
date_strings <- c("2023-05-14", "2021-11-02") years <- as.integer(substr(date_strings, 1, 4))This works only if the string always starts with the year. For other formats, stick with the first two methods.
-
Apply to a data frame column.
In practice, your dates will likely be in a data frame. Use
mutate()fromdplyror base R's$assignment:df$year <- as.numeric(format(df$date_col, "%Y"))or with dplyr
library(dplyr) df <- df %>% mutate(year = year(date_col)) -
Handle non-standard date formats.
If your dates are in formats like "14/05/2023" (day/month/year), you need to specify the format when converting to Date:
dates <- as.Date("14/05/2023", format = "%d/%m/%Y") years <- year(dates)Always check the
formatargument to avoid errors.
Common Mistakes
- Forgetting to convert character strings to Date. Using
year()on a character vector will throw an error. Always convert withas.Date()first. - Using the wrong format specifier.
%Ygives the four-digit year (e.g., 2023), while%ygives the two-digit year (e.g., 23). Mixing them up is a frequent error. - Assuming the year is numeric.
format()returns a character string. If you try to do arithmetic on it, you'll get unexpected results. Convert withas.numeric(). - Not accounting for time zones. If your dates are
POSIXctwith time zones, the year might differ near midnight. Uselubridate::year()which handles this correctly.
Tips
- Use
lubridatefor consistency. It's part of the tidyverse and integrates well with dplyr and ggplot2. - If you need the year as a factor for grouping, wrap the result in
factor(). - For large datasets,
format()can be slower thanlubridate::year(). Benchmark if performance matters. - Always inspect the output with
head()orstr()to confirm you got the expected type (numeric vs character).
Troubleshooting
- Error: "object 'year' not found" – This means you haven't loaded
lubridate. Runlibrary(lubridate)or uselubridate::year()explicitly. - Error: "character string is not in a standard unambiguous format" – Your date strings don't match R's default format (YYYY-MM-DD). Use
as.Date()with theformatargument. - Getting NA values after extraction – Check if your original dates contain missing values. You can filter them out with
!is.na(dates)before extracting. - The result is a list instead of a vector – This happens if you use
lapply()orsapply()incorrectly. Usevapply()or simply apply the function directly to the vector.
Frequently Asked Questions
Can I extract the year from a datetime (POSIXct) object?
Yes. Both format() and lubridate::year() work on POSIXct objects. For example, year(as.POSIXct("2023-05-14 10:30:00")) returns 2023.
What if my dates are in a different format like "May 14, 2023"?
You need to specify the format when converting to Date. Use as.Date("May 14, 2023", format = "%B %d, %Y") then extract the year.
How do I extract the year from a column in a data frame?
Use df$year <- year(df$date) or with dplyr: df <- df %>% mutate(year = year(date)).
Is there a way to get the year as a factor?
Yes, wrap the result with factor(). For example: factor(year(dates)).
Why does format() return a character?
Because format() is designed for formatting output as text. If you need numeric, use as.numeric() or use lubridate::year() which returns a numeric vector.
Can I extract just the last two digits of the year?
Yes, use format(dates, "%y") or as.numeric(format(dates, "%y")). Note that this is not recommended for data analysis due to the Y2K problem.