假设Date 字段属于Date 类的注释中可重复显示的输入——如果不是,则按照注释中所示进行转换。下面展示了各种方法。前两个转换Date 列(看起来更容易),后两个转换Month 列。
1) yearqtr 将Date 转换为yearqtr 对象。使用 cycle 将给出季度(1、2、3 或 4),然后我们可以将季度编号索引到 seasons。
library(zoo)
seasons <- c("Winter", "Spring", "Summer", "Fall")
transform(DF, Season = seasons[cycle(as.yearqtr(Date))])
## Date Month Temperature Season
## 1 2016-07-01 July 13 Summer
## 2 2017-01-08 January 5 Winter
## 3 2018-09-19 September 11 Summer
## 4 2019-10-24 October 9 Fall
如果只使用季度数字就可以了,那么这个单行就足够了。
transform(DF, Season = cycle(as.yearqtr(Date)))
2) Quarters 我们也可以使用quarters 函数仅使用base R 来实现,该函数返回Q1、Q2、Q3 或Q4 作为给定的字符串一个约会。在这种情况下,我们需要确保 Seasons.Q 使用这些名称以便使用它进行查找。
Seasons.Q <- c(Q1 = "Winter", Q2 = "Spring", Q3 = "Summer", Q4 = "Fall")
transform(DF, Season = Seasons.Q[quarters(Date)])
如果使用 Q1、Q2、Q3、Q4 代替名称是可以的,那么我们可以将其简化为单行:
transform(DF, Season = quarters(Date))
3) 匹配 上面使用了日期字段。我们还可以使用 Month 字段作为输入,将其转换为月份编号 1、2、3、...、12,然后将其转换为可以索引到上面定义的 seasons 的季度数。
transform(DF, Season = seasons[(match(Month, month.name) - 1) %/% 3 + 1])
如果一个季度数字而不是季节名称就足够了,那么我们可以将其简化为这个单行:
transform(DF, Season = (match(DF$Month, month.name) - 1) %/% 3 + 1)
4) 日期格式 我们还可以使用日期格式将月份转换为日期,然后使用quarters 并查找Seasons.Q。
transform(DF, Season = Seasons.Q[quarters(as.Date(paste(DF$Month, "001"), "%B %y%d"))])
注意
Lines <- "
Date Month Temperature
2016-07-01 July 13
2017-01-08 January 5
2018-09-19 September 11
2019-10-24 October 9"
DF <- read.table(text = Lines, header = TRUE)
DF$Date <- as.Date(DF$Date)