-1

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

4

1 回答 1

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
于 2013-07-09T11:19:46.683 回答