-1
#make a horrible data frame:

ottawadates <- as.Date(c("2016-08-04", "2016-09-03", "2016-02-15", "2016-03-29, "2016-09-27"))
othervariable <- c(1, 2, 4, 5, 6)
df = data.frame(othervariable, ottawadates)

Okay, so all I'd like to do is create a new field called 'seasons'. I would like to use ranges of dates to indicate which dates belong to corresponding seasons. Just to be clear, my actual data set has the dates in a proper date format so I'm guessing indexing date ranges is fairly straightforward.

i.e. December 21st - March 19th is WINTER. March 20 - June 20th is SPRING June 21st - September 21 is SUMMER September 23 - December 20 is FALL

I feel like this is a for loop job, but I'm too novice to know how to go about it.

Thanks. I appreciate it!

hmnoidk
  • 545
  • 6
  • 20
  • 2
    You'll get a better answer if your example includes the data in the same format as your data. So if your data set uses dates, use dates in your example. – De Novo Mar 06 '18 at 21:24
  • 1
    seems related: https://stackoverflow.com/questions/36502140/determine-season-from-date-using-lubridate-in-r – MrFlick Mar 06 '18 at 21:24
  • 1
    also related: https://stackoverflow.com/questions/9500114/find-which-season-a-particular-date-belongs-to – MrFlick Mar 06 '18 at 21:25
  • Thanks for the suggestions. I updated the sample data so it assumes date format. As for the links, thanks. I'm just confused how to use these chunks so that they iterate through my own dataset and add the right season to the corresponding row in the new 'seasons' column. – hmnoidk Mar 06 '18 at 21:36

1 Answers1

1

You can use lubridate and ifelse to find season based on date range. Assuming seasons as Winter and Other season one approach could be as:

#data
ottawadates <- as.Date(c("2016-08-04", "2016-09-03", "2016-02-15"))
othervariable <- c(1, 2, 4)
df = data.frame(othervariable, ottawadates)

library(lubridate)
df$ottawadates <- ymd(df$ottawadates)

#Evaluate season
df$season <- ifelse((month(df$ottawadates) %in% c(1, 2)) |
                  (month(df$ottawadates) == 12L & day(df$ottawadates) >= 21L) |
                  (month(df$ottawadates) == 3L & day(df$ottawadates) <= 19L),
                  "Winter", 
                  ifelse( (month(df$ottawadates) %in% c(4, 5)) |
                  (month(df$ottawadates) == 3L & day(df$ottawadates) >= 20L) |
                  (month(df$ottawadates) == 6L & day(df$ottawadates) <= 20L),
                   "Spring",
                   ifelse( (month(df$ottawadates) %in% c(7, 8)) |
                           (month(df$ottawadates) == 6L & day(df$ottawadates) >= 21L) |
                           (month(df$ottawadates) == 9L & day(df$ottawadates) <= 21L),
                           "Summer", "Fall")))


df
#  othervariable ottawadates  season
#1             1  2016-08-04  Summer
#2             2  2016-09-03  Summer
#3             4  2016-02-15  Winter
MKR
  • 19,739
  • 4
  • 23
  • 33