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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With