The as.yearmon()
function (and the "yearmon"
class) in package zoo is designed for this sort of data:
dat <- c("2009-Sep","2009-Feb","2009-Jan")
require(zoo)
d2 <- as.yearmon(dat, "%Y-%b")
> sort(d2)
[1] "Jan 2009" "Feb 2009" "Sep 2009"
> order(d2)
[1] 3 2 1
> d2[order(d2)]
[1] "Jan 2009" "Feb 2009" "Sep 2009"
You could of course paste0()
a day onto each date and coerce to class "Date"
via as.Date()
but as.yearmon()
seems more natural to me:
> as.Date(paste0(dat, "-01"), "%Y-%b-%d")
[1] "2009-09-01" "2009-02-01" "2009-01-01"
Note you can generate that same result by coercing the "yearmon"
object to class "as.Date"
, e.g.:
> as.Date(d2)
[1] "2009-09-01" "2009-02-01" "2009-01-01"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…