I have a large data file where all dates were loaded as characters. I would like to change all Dates columns in date format. Most dates have the format "% y% m% d", some have the format "% Y% m% d". There are 25 date columns, so changing each of them is individually inefficient.
I can do
df$DATE1 <- as.Date(df$DATE1, format ="%y%m%d")
df$DATE2 <- as.Date(df$DATE2, format ="%y%m%d")
etc., but very bad coding.
I tried the following code, but it does not work. This assumes all dates are in the format "% y% m% d". Using grep ("DATE", names (df)) will get all Dates columns
df[ , grep("DATE", names(df))] <- as.Date(df[ , grep("DATE", names(df))], "%y%m%d")
source
share