In sample below the new_date column is in the expected format, the date column is in the chr format and the date is stored in it as a number. Is there a way to convert date time (char) to date time format without creating a new column?
df <- data.frame(id = c(1,2),
date = c("2013-09-15T00:00:00Z", "2014-09-13T00:00:00Z"), stringsAsFactors = F)
is.convertible.to.date <- function(x) !is.na(as.Date(as.character(x), tz = Sys.timezone(), format = '%Y-%m-%dT%H:%M:%SZ'))
str(df)
'data.frame': 2 obs. of 2 variables:
id : num 1 2
date: chr "2013-09-15T00:00:00Z" "2014-09-13T00:00:00Z"
DF_date <- sapply(df, is.convertible.to.date)
df$new_date <- as.Date(df[DF_date])
str(df)
'data.frame': 2 obs. of 3 variables:
id : num 1 2
date : chr "2013-09-15T00:00:00Z" "2014-09-13T00:00:00Z"
new_date: Date, format: "2013-09-15" "2014-09-13"
DF_date <- sapply(df, is.convertible.to.date)
df[DF_date] <- as.Date(df[DF_date])
str(df)
'data.frame': 2 obs. of 3 variables:
id : num 1 2
date : chr "15963" "16326"
new_date: Date, format: "2013-09-15" "2014-09-13"
df$date <- as.Date(df$date, tz = Sys.timezone(), format = '%Y-%m-%dT%H:%M:%SZ')
– nevrome