简体   繁体   中英

Converting character variable in date format

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 !

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)

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM