0
votes

I have a continuous list of dates (yyyy-mm-dd) from 1985 to 2018 in one column (Colname = date). What I wish to do is generate another column which outputs a water season and year given the date.

To make it clearer I have two water season: Summer = yyyy-04-01 to yyyy-09-31; Winter = yyyy-10-01 to yyyy(+1)-03-31.

So for 2018 - Summer = 2018-04-01 to 2018-09-31; Winter 2018-10-01 to 2019-03-31.

What I would like to output is something like the following:

enter image description here

Many thanks.

2
At the moment, there's nothing here than a feature list - please add what you have tried, and where exactly you are stuck. Also please avoid data images.jay.sf

2 Answers

2
votes

A tidy verse approach

library(tidyverse)
df <-tibble(date = seq(from = as.Date('2000-01-01'), to = as.Date('2001-12-31'), by = '1 month'))
df
df %>% 
  mutate(water_season_year = case_when(
    lubridate::month(date) %in% c(4:9) ~str_c('Su_', lubridate::year(date)),
    lubridate::month(date) %in% c(10:12) ~str_c('Wi_', lubridate::year(date)),
    lubridate::month(date) %in% c(1:3)~str_c('Wi_', lubridate::year(date) -1),
    TRUE ~ 'Error'))
1
votes

You can compare just the month part of the data to get the season, in base R consider doing

month <- as.integer(format(df$date, "%m"))
year <- format(df$date, "%Y")
inds <- month >= 4 & month <= 9
df$water_season_year <- NA
df$water_season_year[inds] <- paste("Su", year[inds], sep = "_")
df$water_season_year[!inds] <- paste("Wi", year[!inds], sep = "_")
#To add previous year for month <= 3 do
df$water_season_year[month <= 3] <- paste("Wi", 
                         as.integer(year[month <= 3]) - 1, sep = "_")

df
#        date water_season_year
#1 2019-01-03           Wi_2019
#2 2000-06-01           Su_2000

Make sure that date variable is of "Date" class.

data

df <-data.frame(date = as.Date(c("2019-01-03", "2000-06-01")))