-1

I have a short code in R that I want to use to convert the system time to seasons, please can anyone correct it for me?


if ( months(as.POSIXct(system_time, format = "%Y-%m-%d %H:%M:%OS")) == c(12,1,2))
                {season_of_yr <- "Winter"}
            
else if ( months(as.POSIXct(system_time, format = "%Y-%m-%d %H:%M:%OS")) == c(3,4,5)) 
    {season_of_yr <- "Spring"}
else if ( months(as.POSIXct(system_time, format = "%Y-%m-%d %H:%M:%OS")) == c(6,7,8)) 
    {season_of_yr <- "Summer"}
else 
    {season_of_yr <- "Autumn"}

            season <- c(season, season_of_yr)
print(season)

The error message that it shows is:

Error in parse(text = x, srcfile = src): :6:1: unexpected 'else' 5:
6: else ^ Traceback:

Tayo
  • 1
  • Use %in% rather than == . Also use ifelse rather than if. So many duplicates of this but it would be rather difficult to recommend a good search strategy. – IRTFM Apr 24 '22 at 20:25
  • This appears to have answers the to an equivalent question: https://stackoverflow.com/questions/24946955/format-date-time-as-seasons-in-r – IRTFM Apr 24 '22 at 21:43

1 Answers1

0
require(tidyverse)
require(lubridate)

df <- tibble(dates = seq(today(), today() %m+% years(1), by = "week"))

Example data:

# A tibble: 53 x 1
   dates     
   <date>    
 1 2022-04-24
 2 2022-05-01
 3 2022-05-08
 4 2022-05-15
 5 2022-05-22
 6 2022-05-29
 7 2022-06-05
 8 2022-06-12
 9 2022-06-19
10 2022-06-26
# ... with 43 more rows


df %>%
  mutate(
    month = month(dates),
    season = case_when(
      month %>% str_detect("12|1|2") ~ "winter",
      month %>% str_detect("3|4|5") ~ "spring",
      month %>% str_detect("6|7|8") ~ "summer",
      TRUE ~ "autumn"
    )
  )

Output:

# A tibble: 53 x 3
   dates      month season
   <date>     <dbl> <chr> 
 1 2022-04-24     4 spring
 2 2022-05-01     5 spring
 3 2022-05-08     5 spring
 4 2022-05-15     5 spring
 5 2022-05-22     5 spring
 6 2022-05-29     5 spring
 7 2022-06-05     6 summer
 8 2022-06-12     6 summer
 9 2022-06-19     6 summer
10 2022-06-26     6 summer
# ... with 43 more rows
Chamkrai
  • 5,912
  • 1
  • 4
  • 14