Search code examples
stringrindices

R make index with dayseries as string data?


I have a string data with following characteristic
c = ("19790102", "19790103", "19790104", "19790105",...).

Now I want to make an index for the different seasons (summer, autumn, winter, spring). I managed to do that with only one month (e.g september):

ind_september=which(as.numeric(substr(dayserie[],5,6))==9)

But I have no idea how to do that with several month to get an index for seasons.

Has someone an idea?


Solution

  • Using Find which season a particular date belongs to , I slithly change the function to add a format argument:

    getSeason <- function(DATES,frmt = "%Y%m%d") {
      WS <- as.POSIXct("2012-12-21", format = "%Y-%m-%d") # Winter 
      SE <- as.POSIXct("2012-3-21",  format = "%Y-%m-%d") # Spring 
      SS <- as.POSIXct("2012-6-21",  format = "%Y-%m-%d") # Summer 
      FE <- as.POSIXct("2012-9-21",  format = "%Y-%m-%d") # Autumn 
    
      # Convert dates from any year to 2012 dates
      d <- strftime(as.POSIXct(DATES, format=frmt),
                    format='2012-%m-%d')
    
      ifelse (d >= WS | d < SE, "Winter",
              ifelse (d >= SE & d < SS, "Spring",
                      ifelse (d >= SS & d < FE, "Summer", "Fall")))
    }
    
    dayserie <- c("19790102", "19790103", "19790104", "19790105")
    getSeason(dayserie,'%Y%m%d')
    
    "Winter" "Winter" "Winter" "Winter"