R语言:为数据框新增列并按月份分组划分季节
Hey there, let's get that Season column added to your weather_grouped tibble. Mapping months to seasons is a common task, and there are a couple of clean ways to do this with R's tidyverse tools (since you're working with a tibble, I assume you're already using dplyr). Here are my go-to approaches:
1. Use case_when() for explicit, readable logic
This method is great because it's super clear exactly which months map to which season—no guessing about interval boundaries.
library(dplyr) # Update the tibble with the new Season column weather_grouped <- weather_grouped %>% mutate(Season = case_when( Month %in% 1:3 ~ "冬季", # Jan-Mar Month %in% 4:6 ~ "春季", # Apr-Jun Month %in% 7:9 ~ "夏季", # Jul-Sep Month %in% 10:12 ~ "秋季", # Oct-Dec TRUE ~ NA_character_ # Catch any unexpected Month values ))
The TRUE ~ NA_character_ line is a safety net—if you have any Month values outside 1-12, they'll get marked as NA instead of breaking the code.
2. Use cut() for concise interval-based grouping
If you prefer a more compact approach, cut() works perfectly here since we're dealing with continuous month values that fit cleanly into fixed intervals.
weather_grouped <- weather_grouped %>% mutate(Season = cut( x = Month, breaks = c(0, 3, 6, 9, 12), # Define the interval boundaries labels = c("冬季", "春季", "夏季", "秋季"), # Match labels to intervals include.lowest = TRUE # Ensure Month=1 is included in the first interval ))
The include.lowest = TRUE is important here—it makes sure that the lowest value (1) falls into the first interval (0-3) instead of being excluded.
Verify the result
Once you run either of these, you can check the updated tibble with:
head(weather_grouped)
You should see the new Season column populated with the correct season for each row's Month value.
内容的提问来源于stack exchange,提问作者Sara Hanna

