So we start by separating the two:
x <- c("03/20/2018 10:42", "2018-03-20 10:37:02")
DF <- data.frame(x = x, stringsAsFactors = FALSE)
slash_index <- grep("/", DF$x)
slash <- DF$x[slash_index]
dash <- DF$x[-slash_index]
Then we convert them. I like lubridate, but you can use your method if you'd like
library(lubridate)
slash <- mdy_hm(slash)
dash <- ymd_hms(dash)
Then we put them into a date vector:
date_times <- integer(0)
date_times[slash_index] <- slash
date_times[seq_along(DF$x)[-slash_index]] <- dash
DF$x <- as.POSIXct(date_times, origin = "1970-01-01 00:00:00")
DF
# x
# 1 2018-03-20 03:42:02
# 2 2018-03-20 03:37:02
Note:
The tricky part here was re-assigning parts of a vector to a vector according to their index. When a portion of a vector was assigned to a POSIXct
object, it had its attributes stripped, turning it into the internal integer code for the date time. This was resolved by stripping the attributes at the beginning, and then re-assigning the class at the end.
Here's the full thing with your example:
install.packages("lubridate")
library(lubridate)
x <- c("6/21/2006 0:00",
"1889-06-13 00:00:00",
"6/28/2012 0:00",
"5/19/2015 0:00",
"6/6/2016 0:00",
"1884-05-24 00:00:00",
"7/28/2013 0:00")
DF <- data.frame(x = x, stringsAsFactors = FALSE)
slash_index <- grep("/", DF$x)
slash <- DF$x[slash_index]
dash <- DF$x[-slash_index]
slash <- mdy_hm(slash)
dash <- ymd_hms(dash)
date_times <- integer(0)
date_times[slash_index] <- slash
date_times[seq_along(DF$x)[-slash_index]] <- dash
DF$x <- as.POSIXct(date_times, origin = "1970-01-01 00:00:00", tz = "UTC")
DF
# x
# 1 2006-06-21
# 2 1889-06-13
# 3 2012-06-28
# 4 2015-05-19
# 5 2016-06-06
# 6 1884-05-24
# 7 2013-07-28
Because the times for these are all "00:00:00"
, they've been truncated. You can display them with the "00:00:00"
using the method described in answers to this question.