Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

r - R:如何将季节分配给月份(因子)(R: how to assign seasons to months (factor))

in my dataset I have the following vector of months:

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

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

I would like to assign a vector of 4 seasons to each month.

(我想为每个月分配4个季节的向量。)

I tried case when/ if else (neither of these work).

(我尝试了case when / if else(这两项都不起作用)。)

Any suggestions how to solve this issue?

(有什么建议如何解决这个问题?)

Many thanks, Kasia

(非常感谢,Kasia)

  ask by Katarzyna Rembeza translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...