[英]R: how to assign seasons to months (factor)
在我的數據集中,我有以下月份向量:
bank$month <-factor(bank$month,
levels = c("jan", "feb", "mar", "apr", "may", "jun",
"jul", "aug", "sep", "oct", "nov", "dec"))
我想為每個月分配一個 4 個季節的向量。 我嘗試過 case when/if else(這些都不起作用)。 任何建議如何解決這個問題?
非常感謝,卡西亞
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
語句手動執行此操作,但為什么要重新發明輪子!
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'))
您可以使用(forcats)
:
library(tidyverse)
bank %>% fct_recode(month, "A" = "jan", "A" = "feb")
...等等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.