convert date (yyyy-mm-dd) into Year only

How you change date format to only year? what functions shoud I use

Hi @saad_el_eulj,
Welcome to the RStudio Community Forum.

Here is a simple way to extract the year from a date, and deliver the result as a number, using the year() function from the {lubridate} package:

#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#>     date, intersect, setdiff, union
#> [1] 2015

Created on 2021-05-25 by the reprex package (v2.0.0)

how can you convert if you already have a column date example row : 2015-01-01 to only 2015

You can use str_sub() from the stringr package


x <- Sys.Date()
#> [1] "2021-05-25"

the_year <- stringr::str_sub(string = x, start = 1, end = 4)
#> [1] "2021"

#> [1] "character"

# Optionally - if you want year to be numeric

Hi @Dobrokhotov1989
let's say i alrady have a date column that I want to convert it to only year.
Example of the row format: 2015-01-01 I want only to keep the 2015 and drop month and days.

How is it different from the example I've provided?
In case of a data.frame you just apply str_sub() function to you date column


df %>%
  mutate(year = stringr::str_sub(string = date, start = 1, end = 4))

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.