【问题标题】:R: how to assign seasons to months (factor)R:如何将季节分配给月份(因子)
【发布时间】:2019-12-01 16:32:32
【问题描述】:

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

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

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

非常感谢,卡西亚

【问题讨论】:

标签: r date


【解决方案1】:

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 语句手动执行此操作,但为什么要重新发明轮子!

【讨论】:

    【解决方案2】:
    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'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多