Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating season variable by month with dplyr in R

Tags:

r

dplyr

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!

like image 265
newbie14 Avatar asked Dec 23 '22 08:12

newbie14


1 Answers

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"))
like image 106
Tung Avatar answered Jan 08 '23 04:01

Tung