Home > Net >  Can't figure out how to change "X5.13.1996" to date class?
Can't figure out how to change "X5.13.1996" to date class?

Time:03-05

I have dates listed as "X5.13.1996", representing May 13th, 1996. The class for the date column is currently a character.

When using mdy from lubridate, it keeps populating NA. Is there a code I can use to get rid of the "X" to successfully use the code? Is there anything else I can do?

CodePudding user response:

Is there anything else I can do?

Try strptime

x <- "X5.13.1996"
strptime(x, "X%m.%d.%Y")
# [1] "1996-05-13 CEST"

CodePudding user response:

You can use substring(date_variable, 2) to drop the first character from the string.

substring("X5.13.1996", 2)

[1] "5.13.1996"

To convert a variable (i.e., column) in your data frame:

library(dplyr)
library(lubridate)

dates <- data.frame(
  dt = c("X5.13.1996", "X11.15.2021")
)

dates %>% 
  mutate(converted = mdy(substring(dt, 2)))

or, without dplyr:

dates$converted <- mdy(substring(dates$dt, 2))

Output:

          dt  converted
1  X5.13.1996 1996-05-13
2 X11.15.2021 2021-11-15
  • Related