Extract Year from a Column in a Dataframe

 

To extract the year from the column, we will create a dataframe with date columns and then separate the year from DateTime using format() methods and extract the year and convert to a numeric format.

 

R




# declaring a data frame
data_frame = data.frame(Rank = c(5:8) ,
                        Time = c("2021-05-05 01:04:34",
                                 "2021-03-06 03:14:44",
                                 "2021-03-11 07:22:48",
                                 "2021-02-02 11:54:56"))
   
print ("Original dataframe")
data_frame
 
# data_frame$year <- as.Date(data_frame$Time, "%Y")
# data_frame
 
data_frame$Time <- as.Date(data_frame$Time)
 
print("Extract year")
# extract the year and convert to numeric format
data_frame$year <- as.numeric(format(data_frame$Time, "%Y"))
data_frame


 

 

Output:

 

[1] "Original dataframe"
Rank    Time
5    2021-05-05 01:04:34
6    2021-03-06 03:14:44
7    2021-03-11 07:22:48
8    2021-02-02 11:54:56

Extract year
Rank    Time    year
5    2021-05-05    2021
6    2021-03-06    2021
7    2021-03-11    2021
8    2021-02-02    2021

 



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

...