TechBuzzPro

How to Get Year from Date in R (3 Easy Ways)

· 4 min read · Apps & Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. or with dplyr
  4. Common Mistakes
  5. Tips
  6. Troubleshooting
  7. Frequently Asked Questions

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 Date objects or character strings
  • For the lubridate method, install the package with install.packages("lubridate")

Step-by-Step

  1. 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 Date or POSIXct format, you can skip this step.

  2. 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"))
  3. Method 2: Use lubridate::year().

    The lubridate package 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.

  4. Method 3: Use as.integer() with substr() (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.

  5. Apply to a data frame column.

    In practice, your dates will likely be in a data frame. Use mutate() from dplyr or 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))
  6. 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 format argument to avoid errors.

Common Mistakes

  • Forgetting to convert character strings to Date. Using year() on a character vector will throw an error. Always convert with as.Date() first.
  • Using the wrong format specifier. %Y gives the four-digit year (e.g., 2023), while %y gives 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 with as.numeric().
  • Not accounting for time zones. If your dates are POSIXct with time zones, the year might differ near midnight. Use lubridate::year() which handles this correctly.

Tips

  • Use lubridate for 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 than lubridate::year(). Benchmark if performance matters.
  • Always inspect the output with head() or str() to confirm you got the expected type (numeric vs character).

Troubleshooting

  • Error: "object 'year' not found" – This means you haven't loaded lubridate. Run library(lubridate) or use lubridate::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 the format argument.
  • 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() or sapply() incorrectly. Use vapply() 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.