Creating season variable by month with dplyr in R

后端 未结 3 539
渐次进展
渐次进展 2021-01-20 05:12

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 trie

3条回答
  •  没有蜡笔的小新
    2021-01-20 05:39

    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"))
    

提交回复
热议问题