[英]Ordering dataframe by month-year date column
I have a dataframe df:我有一个 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:我想要的 output 应该是:
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
您可以通过粘贴任意日期值然后
order
将该列转换为日期 object
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或使用不需要日期的
zoo::as.yearmon
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))),]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.