Convert multiple columns in R data frame to date format

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")
+4
source share
1 answer

Try:

df[, cols <- grep("^DATE", names(df))] <- lapply(df[, cols <- grep("^DATE", names(df))], as.Date, format = "%y%m%d")

Example:

df <- data.frame(DATE1 = c('910812', '900928'), DATE2 = c('890813', '890910'))
# Apply the above and you get:
# > df
#        DATE1      DATE2
# 1 1991-08-12 1989-08-13
# 2 1990-09-28 1989-09-10
# > class(df[, 1])
# [1] "Date"
+8
source

Source: https://habr.com/ru/post/1534330/


All Articles