Format date-time as seasons in R?

后端 未结 4 1274
夕颜
夕颜 2020-12-04 01:51

In R, it\'s possible to format POSIXlt date-time objects as a month:

format(Sys.time(), format=\'%Y-%m\')

Is there a way to do the same thi

4条回答
  •  执念已碎
    2020-12-04 02:18

    Let Q1 be DJF; Q2, MAM; etc. then:

    seasonal.quarters <- function(x) {
        x <- as.POSIXlt(x)
        x$mon <- (x$mon + 1) %% 12
        quarters(x)
    }
    
    options(stringsAsFactors=FALSE)
    
    nonleap.year <- seq(from=as.POSIXct('2013-1-1'), to=as.POSIXct('2014-1-1'), by='day')
    d <- data.frame(ms=months(nonleap.year), qs=seasonal.quarters(nonleap.year))
    by(d, INDICES=list(d$qs), FUN=function(x) unique(x$ms))
    # : Q1
    # [1] "January"  "February" "December"
    # -------------------------------------
    # : Q2
    # [1] "March" "April" "May"  
    # -------------------------------------
    # : Q3
    # [1] "June"   "July"   "August"
    # -------------------------------------
    # : Q4
    # [1] "September" "October"   "November" 
    
    leap.year <- seq(from=as.POSIXct('2016-1-1'), to=as.POSIXct('2017-1-1'), by='day')
    d <- data.frame(ms=months(leap.year), qs=seasonal.quarters(leap.year))
    by(d, INDICES=list(d$qs), FUN=function(x) unique(x$ms))
    # : Q1
    # [1] "January"  "February" "December"
    # -------------------------------------
    # : Q2
    # [1] "March" "April" "May"  
    # -------------------------------------
    # : Q3
    # [1] "June"   "July"   "August"
    # -------------------------------------
    # : Q4
    # [1] "September" "October"   "November" 
    

提交回复
热议问题