I have a dataset that has a variable called month, which each month as a character. Is there a way with dplyr to combine some months to create a season variable? I have tried the following but got an error:
data %>%
mutate(season = ifelse(month[1:3], "Winter", ifelse(month[4:6], "Spring",
ifelse(month[7:9], "Summer",
ifelse(month[10:12], "Fall", NA)))))
With error:
Error in mutate_impl(.data, dots) : Column `season` must be length 100798 (the number of rows) or one, not 3
I am new to R so any help is much appreciated!
The correct syntax should be
data %>% mutate(season = ifelse(month %in% 10:12, "Fall",
ifelse(month %in% 1:3, "Winter",
ifelse(month %in% 4:6, "Spring",
"Summer"))))
Edit: probably a better way to get the job done
Astronomical Seasons
temp_data %>%
mutate(
season = case_when(
month %in% 10:12 ~ "Fall",
month %in% 1:3 ~ "Winter",
month %in% 4:6 ~ "Spring",
TRUE ~ "Summer"))
Meteorological Seasons
temp_data %>%
mutate(
season = case_when(
month %in% 9:11 ~ "Fall",
month %in% c(12, 1, 2) ~ "Winter",
month %in% 3:5 ~ "Spring",
TRUE ~ "Summer"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With