The forcats
package has a lot of convenience functions for these kinds of factor manipulations.
(forcats
软件包具有许多方便的功能,可用于这些类型的因子操作。)
I'd suggest the fct_collapse
function, which lets you define levels of a new (less granular) factor based on levels of another factor or character vector: (我建议使用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)
You could do this manually with a switch
statement, but why re-invent the wheel!
(您可以使用switch
语句手动完成此操作,但是为什么要重新发明轮子呢!)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…