Extract Year from a Vector

In this method, the as.POSIXct is a Date-time Conversion Functions that is used to manipulate objects of classes. To extract the year from vector we need to create a vector with some dates and then arrange the date with as.POSIXct() and  get year with format() methods.

R




Date <- c("01/12/2011 12:40:00", "11/12/2015 11:40:00",
          "01/02/2012 05:40:00", "01/04/2021 09:44:00" ,
          "01/02/2020 01:43:00", "01/12/2014 04:41:00")
 
print("Vector Date:")
print(Date)
 
# formatted date
print("Extract Year:")
Date <- as.POSIXct(Date, format = "%m/%d/%Y %H:%M:%S")
format(Date, format="%Y")


 

 

Output:

 

[1] "Vector Date:"
[1] "01/12/2011 12:40:00" "11/12/2015 11:40:00" "01/02/2012 05:40:00"
[4] "01/04/2021 09:44:00" "01/02/2020 01:43:00" "01/12/2014 04:41:00"

[1] "Extract Year:"
'2011' '2015' '2012' '2021' '2020' '2014'

How to Extract Year from Date in R

In this article, we are going to see how to extract the year from the date in R Programming Language.

Similar Reads

Method 1:  Extract Year from a Vector

In this method, the as.POSIXct is a Date-time Conversion Functions that is used to manipulate objects of classes. To extract the year from vector we need to create a vector with some dates and then arrange the date with as.POSIXct() and  get year with format() methods....

Method 2: Extract Year from a Column in a Dataframe

...