سؤال

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?

هل كانت مفيدة؟

المحلول

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"

نصائح أخرى

You may also check the seas package.

library(seas)

x <- c("19790304", "19790603", "19790903",  "19791205")

x2 <- as.Date(x, format = "%Y%m%d")

# width = "JFM": annual quarterly divisions: JFM, AMJ, JAS, OND
x3 <- mkseas(x2, width = "JFM")
x3
# [1] JFM AMJ JAS OND

# if you wish to rename factor levels
x4 <- factor(x3, labels = c("winter", "spring", "summer", "autumn"))
x4
# [1] winter spring summer autumn

# alternative division
# width = "DJF": meteorological quarterly divisions: DJF, MAM, JJA, SON
x3 <- mkseas(x2, width = "DJF")
x3
# [1] MAM JJA SON DJF

x4 <- factor(x3, labels = c("winter", "spring", "summer", "autumn"))
x4
# [1] spring summer autumn winter
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top