简体   繁体   中英

Ordering dataframe by month-year date column

I have a dataframe df:

date        values
Apr-15        86
Apr-16        80
Apr-17        60
Aug-14        88
Aug-15        52
Aug-16        76

My desired output should be:

 date        values
Aug-14        88
Apr-15        86
Aug-15        52
Apr-16        80
Aug-16        76
Apr-17        60 

My date format is different so I am unable to do it.

You can convert the column into date object by pasting an arbitrary date value and then order

df[order(as.Date(paste0("1-", df$date), "%d-%b-%y")), ]

#    date values
#4 Aug-14     88
#1 Apr-15     86
#5 Aug-15     52
#2 Apr-16     80
#6 Aug-16     76
#3 Apr-17     60

Or using zoo::as.yearmon which will not require date

df[order(zoo::as.yearmon(df$date, "%b-%y")), ]

data

df <- structure(list(date = structure(1:6, .Label = c("Apr-15", "Apr-16", 
"Apr-17", "Aug-14", "Aug-15", "Aug-16"), class = "factor"), values = c(86L, 
80L, 60L, 88L, 52L, 76L)), class = "data.frame", row.names = c(NA, -6L))

You can try with

df[with(df,order(gsub("[^0-9]","",date))),]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM