在R中添加基于日期的季节因子

时间:2013-07-09 09:36:22

标签: r

我如何根据R中的日期添加季节作为因素?我有一张日期为4年的表格,我必须添加一个列季,它将查看日期的月份和日期,并确定它是哪个季节。无论一年如何,我都会为每个季节安排一些固定日期。

1 个答案:

答案 0 :(得分:1)

我建议quarter()包中的lubridate

library(lubridate)
dates <- structure(c(15238, 15730, 15362, 15478, 15764, 15635, 15372, 
                     15768, 15243, 15377), class = "Date") # example data
dates
# > dates
# [1] "2011-09-21" "2013-01-25" "2012-01-23" "2012-05-18" "2013-02-28" "2012-10-22" "2012-02-02"
# [8] "2013-03-04" "2011-09-26" "2012-02-07"
dates <- as.data.frame(dates)
dates$q <- quarter(dates$dates)
# dates q
# 1  2011-09-21 3
# 2  2013-01-25 1
# 3  2012-01-23 1
# 4  2012-05-18 2
# 5  2013-02-28 1
# 6  2012-10-22 4
# 7  2012-02-02 1
# 8  2013-03-04 1
# 9  2011-09-26 3
# 10 2012-02-07 1
dates$season <- NA # If you really want seasons (string) proceed...
dates <- within(dates, {season[q == 1] <- "spr"
                        season[q == 2] <- "sum"
                        season[q == 3] <- "fall"
                        season[q == 4] <- "win"})
# dates q season
# 1  2011-09-21 3   fall
# 2  2013-01-25 1    spr
# 3  2012-01-23 1    spr
# 4  2012-05-18 2    sum
# 5  2013-02-28 1    spr
# 6  2012-10-22 4    win
# 7  2012-02-02 1    spr
# 8  2013-03-04 1    spr
# 9  2011-09-26 3   fall
# 10 2012-02-07 1    spr