R:如何将季节分配给月份(因子)

时间:2019-12-01 16:32:32

标签: r date

在我的数据集中,我有以下几个月的向量:

bank$month <-factor(bank$month, 
                       levels = c("jan", "feb", "mar", "apr", "may", "jun",
                                  "jul", "aug", "sep", "oct", "nov", "dec"))

我想为每个月分配4个季节的向量。 我尝试了case when / if else(这两项都不起作用)。有什么建议可以解决这个问题吗?

非常感谢,Kasia

2 个答案:

答案 0 :(得分:2)

forcats软件包具有许多方便的功能,可用于这些类型的因子操作。我建议使用fct_collapse函数,该函数可让您根据另一个因子或字符向量的水平来定义新的(较少粒度的)因子的水平:

library(dplyr)
library(forcats)

dates = tibble(
  month = factor(sample(month.abb,40,replace = TRUE),levels = month.abb)
)
dates = dates %>% mutate(
  season = fct_collapse(
    month,
    'Spring' = month.abb[3:5],
    'Summer' = month.abb[6:8],
    'Fall' = month.abb[9:11],
    'Winter' = month.abb[c(12,1,2)]
  )
)

# check them:
table(dates$month,dates$season)

您可以使用switch语句手动完成此操作,但是为什么要重新发明轮子呢?

答案 1 :(得分:1)

library(tidyverse)    
bank %>%
      mutate(Month_No = match(str_to_title(month), month.abb)) %>%
      mutate(Season = case_when(Month_No %in% 3:5 ~ 'Spring',
                                Month_No %in% 6:8 ~ 'Summer',
                                Month_No %in% 9:11 ~ 'Autumn',
                                TRUE ~ 'Winter'))