Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert string to date type with lubridate in r

Tags:

r

lubridate

I have a column dateofbirth contain string type of date such as 11-12-89, I want to convert it to date type in order to use lubridate::year() to extract the year. I am wondering how to convert this to date format like 11/12/1989 ). By the way, when use fwrite() to output the csv file and read in excel show the dateofbirth is something like "11/12/1989", but in r when use fread to read the original file the dateofbirth is like "11-12-89".

Thank you in advance.

like image 504
J.ZHONG Avatar asked Oct 12 '25 01:10

J.ZHONG


1 Answers

Assuming the date format that you have is date-month-year.

In base R, you can use :

#Convert to date
df$dateofbirth <- as.Date(df$dateofbirth, '%d-%m-%y')
#Get the year
df$year <- as.integer(format(df$dateofbirth, "%Y"))

OR with lubridate

library(lubridate)
df$dateofbirth <- dmy(df$dateofbirth)
df$year <- year(df$dateofbirth)
like image 97
Ronak Shah Avatar answered Oct 14 '25 18:10

Ronak Shah