Determine season from Date using lubridate in R

后端 未结 6 2057
刺人心
刺人心 2020-12-16 04:46

I have a very big dataset with a DateTime Column containing POSIXct-Values. I need to determine the season (Winter - Summer) based on the DateTime

6条回答
  •  [愿得一人]
    2020-12-16 05:39

    And if you're interested in getting back four seasons, here's code to do that:

    library(lubridate)
    getSeason <- function(input.date){
      numeric.date <- 100*month(input.date)+day(input.date)
      ## input Seasons upper limits in the form MMDD in the "break =" option:
      cuts <- base::cut(numeric.date, breaks = c(0,319,0620,0921,1220,1231)) 
      # rename the resulting groups (could've been done within cut(...levels=) if "Winter" wasn't double
      levels(cuts) <- c("Winter","Spring","Summer","Fall","Winter")
      return(cuts)
    }
    

    Unit Test:

    getSeason(as.POSIXct("2016-01-01 12:00:00")+(0:365)*(60*60*24))
    

提交回复
热议问题