Home > Software engineering >  Converting character variable in date format
Converting character variable in date format

Time:01-05

I'd like to convert my variable "birthdate" from a character class to dates. They're actually written like that "dd/mm/yyyy". I tried to use the function as.Date but I obtained something wrong :

x$age <- as.Date(x$birhtdate)

R doesn't read the character string correctly. For example 21/12/1948 becomes 0021/12/19

I am a bit lost, I also tried to use the function format but without success. Thank for your help !

CodePudding user response:

You can use the R package lubridate to explicitly use specific ordering of day and month:

x <- data.frame(birhtdate = "21/12/1948")

x$birhtdate <- lubridate::parse_date_time(x$birhtdate, orders = "dmy")
x
#>    birhtdate
#> 1 1948-12-21

Created on 2023-01-04 by the reprex package (v2.0.1)

CodePudding user response:

base R answer:

Yes, you need to provide R with the format, there are so much different possibilities like '-' or a space or different order mm/dd/yyyy

So:

as.Date('21/12/1948', format = '%d/%m/%Y')

will work.

Output:

[1] "1948-12-21"
  • Related