2013-07-09 30 views
-1

如何根據R中的日期添加季節作爲因子?我有一張桌子,日期爲4年,我必須添加一個列季節,它將查看日期的月份和日期,並決定它是哪個季節。無論年份如何,我都會爲每個季節確定一些固定日期。根據R中的日期添加季節因子

+1

您可以提供的樣本數據?這很簡單,但精確的解決方案將取決於您的數據是什麼樣子。也許給我們dput(head(df))的輸出,其中'df'是你的數據框。 – Thomas

+0

@ user2563925請讓我知道這是否解決了您的問題。 –

回答

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