Home > Software engineering >  If there are two dataset I need to use but the date format in dataset is different, how could I conv
If there are two dataset I need to use but the date format in dataset is different, how could I conv

Time:11-30

This is the first dataset's date format, it is in "YYYYMMDD" format

This is the first dataset's date format, it is in "YYYYMMDD" format

This is the second dataset's date format, it is in "MDDYY" format This is the second dataset's date format, it is in "MDDYY" format

How could I convert the dates reported in the second dataset to the format used in the first (YYYYMMDD) I got stuck on this question and my code doesn't make sense. Please give me some example for this, the date needs to stay in "as.data.frame

CodePudding user response:

Another option to parse the date is to use the mdy() from package lubridate.

mdy(22601)
# [1] "2001-02-26"
df$date <- mdy(df$date)

CodePudding user response:

Generally, you can specify a date format in as.POSIXct. For example

x <- c("19900104")
as.POSIXct(x, format = "%Y%m%d")

and

x <- c("22601", "110101")
as.POSIXct(ifelse(nchar(x) == 5, paste0("0", x), x), format = "%m%d%y")

as.POSIXct can be used on an entire column vector like so


df$date <- as.POSIXct(df$date, format = ...)
  • Related