我有一个具有以下特征的字符串数据
c = ("19790102", "19790103", "19790104", "19790105",...)
。
现在我想为不同的季节(夏天、秋天、冬天、春天)做一个索引。我只用了一个月(例如九月)就做到了:
ind_september=which(as.numeric(substr(dayserie[],5,6))==9)
但我不知道如何用几个月的时间来获得季节指数。
有人有想法吗?
您也可以检查seas
包裹。
library(seas)
x <- c("19790304", "19790603", "19790903", "19791205")
x2 <- as.Date(x, format = "%Y%m%d")
# width = "JFM": annual quarterly divisions: JFM, AMJ, JAS, OND
x3 <- mkseas(x2, width = "JFM")
x3
# [1] JFM AMJ JAS OND
# if you wish to rename factor levels
x4 <- factor(x3, labels = c("winter", "spring", "summer", "autumn"))
x4
# [1] winter spring summer autumn
# alternative division
# width = "DJF": meteorological quarterly divisions: DJF, MAM, JJA, SON
x3 <- mkseas(x2, width = "DJF")
x3
# [1] MAM JJA SON DJF
x4 <- factor(x3, labels = c("winter", "spring", "summer", "autumn"))
x4
# [1] spring summer autumn winter
使用 Find which season a specific date belongs to,我巧妙地更改了函数以添加格式参数:
getSeason <- function(DATES,frmt = "%Y%m%d") {
WS <- as.POSIXct("2012-12-21", format = "%Y-%m-%d") # Winter
SE <- as.POSIXct("2012-3-21", format = "%Y-%m-%d") # Spring
SS <- as.POSIXct("2012-6-21", format = "%Y-%m-%d") # Summer
FE <- as.POSIXct("2012-9-21", format = "%Y-%m-%d") # Autumn
# Convert dates from any year to 2012 dates
d <- strftime(as.POSIXct(DATES, format=frmt),
format='2012-%m-%d')
ifelse (d >= WS | d < SE, "Winter",
ifelse (d >= SE & d < SS, "Spring",
ifelse (d >= SS & d < FE, "Summer", "Fall")))
}
dayserie <- c("19790102", "19790103", "19790104", "19790105")
getSeason(dayserie,'%Y%m%d')
"Winter" "Winter" "Winter" "Winter"