'Converting Current System Time to Seasons in R
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:
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tom Hoel |
