Format date-time as seasons in R?

后端 未结 4 1271
夕颜
夕颜 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:34

    as.POSIXlt returns a named list (which makes it unsuitable for data.frame columns). The list columns can be individually accessed and include "year" (1900-based, unlike 1970 used for default) and "mon" (0-based). Best place to see this list in hte help system is ?DateTimeClasses:

    First just a Seasons calculation, then a Year-Seasons calculation

     c('DJF', 'MAM', 'JJA', 'SON')[ # select from character vector with numeric vector
              1+((as.POSIXlt(dates)$mon+1) %/% 3)%%4]
    
     [1] "JJA" "JJA" "SON" "SON" "DJF" "DJF" "DJF" "MAM" "MAM" "JJA"
    [11] "JJA"
    
    
    
       paste( 1900 + # this is the base year for POSIXlt year numbering 
                 as.POSIXlt( dates )$year + 
                 1*(as.POSIXlt( dates )$year==12) ,   # offset needed for December
              c('DJF', 'MAM', 'JJA', 'SON')[          # indexing from 0-based-mon
                                 1+((as.POSIXlt(dates)$mon+1) %/% 3)%%4] 
              , sep="-")
     [1] "2014-JJA" "2014-JJA" "2014-SON" "2014-SON" "2014-DJF"
     [6] "2015-DJF" "2015-DJF" "2015-MAM" "2015-MAM" "2015-JJA"
    [11] "2015-JJA"
    

    Shouldn't be that difficult to make a function that constructs the formatting you expect. This is just modulo arithmetic on the POSIXlt values for month and year.

提交回复
热议问题