I have the following data:
df <- data.frame(id = c(0101, 1011, 2301), flat = c(1, 11, 1), buid = c(1, 10, 23), X2019.12.31.23.59.59 = c(14.123, 12.53, 8.53), X2020.01.31.23.59.59 = c(15.03, 14.63, 9.53), X30.04.2019.23.59 = c(21.03, 17.67, 7.27))
I need to arrange the columns in order of the date that is written in the name of the columns.
A general solution would be to separate date and non-date columns, sort the date columns according to this answer and combine them.
library(lubridate)
date_cols <- grep('X\\d+\\.\\d+\\d+', names(df), value = TRUE)
non_date_cols <- grep('X\\d+\\.\\d+\\d+', names(df), value = TRUE, invert = TRUE)
date_cols <- date_cols[order(as.Date(parse_date_time(sub('^X', '',
date_cols), c('YmdHMS', 'dmyHM'))))]
df[c(non_date_cols, date_cols)]
To keep only unique date columns we can do :
cols <- as.Date(parse_date_time(sub('^X', '', date_cols), c('YmdHMS', 'dmyHM')))
df[c(non_date_cols, date_cols[!duplicated(cols)])]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments