生成一天属于哪个 15 天的时间段
Generate which 15-days period a day fall into
我有一个包含年份和日期的数据框
df <- data.frame(year = rep(1980:2015,each = 365), day = 1:365)
请注意,我一年只需要 365 天,即我假设每一天都有
365 年。
我要生成两个数据:
1)每一天属于哪个月
2) 每一天属于哪15天。一年有24个15天。也就是说,每个月都会像这样分成两半;
Jan: 1st - 15th: 1st Quarter
Jan: 16th- 31st: 2nd Quarter
Feb: 1st - 15th: 3rd Quarter
Feb: 16th - 28th: 4th Quarter
March: 1st - 15th: 5th Quarter
.
.
Decmber: 16th - 31st: 24th quarter
我的最终数据应该是这样的
Year Day Quarter Month
1980 1 1 1
1980 2 1 1
.
.
1980 365 24 12
.
.
2015 1 1 1
2015 2 1 1
.
.
2015 365 12 24
我可以用这个生成月份:
library(dplyr)
months <- list(1:31, 32:59, 60:90, 91:120, 121:151, 152:181, 182:212, 213:243, 244:273, 274:304, 305:334, 335:365)
df1 <- df %>% group_by(year) %>%
mutate(month = sapply(day, function(x) which(sapply(months, function(y) x %in% y)))
但是我不知道15天的期限是怎么产生的?
为了处理不应包括闰年的 2 月 29 日的问题,我们可能会生成一个完整的日期序列,然后删除 2 月 29 日的实例。从日期中获取 month
。通过检查 %d
是否为 <= 15
并从 2*
中减去月份数来计算 two-week 周期。
# complete sequence of dates
# use two years in this example, with 2012 being a leap year
dates <- data.frame(date = seq(as.Date("2011-01-01"), as.Date("2012-12-31"), by = "1 day"))
# remove Feb 29th in leap years
d <- dates[format(dates$date, "%m-%d") != "02-29", , drop = FALSE]
# create month
d$month <- month(d$date)
# create two-week number
d$twoweek <- d$month * 2 - (as.numeric(format(d$date, "%d")) <= 15)
我有一个包含年份和日期的数据框
df <- data.frame(year = rep(1980:2015,each = 365), day = 1:365)
请注意,我一年只需要 365 天,即我假设每一天都有 365 年。
我要生成两个数据: 1)每一天属于哪个月 2) 每一天属于哪15天。一年有24个15天。也就是说,每个月都会像这样分成两半;
Jan: 1st - 15th: 1st Quarter
Jan: 16th- 31st: 2nd Quarter
Feb: 1st - 15th: 3rd Quarter
Feb: 16th - 28th: 4th Quarter
March: 1st - 15th: 5th Quarter
.
.
Decmber: 16th - 31st: 24th quarter
我的最终数据应该是这样的
Year Day Quarter Month
1980 1 1 1
1980 2 1 1
.
.
1980 365 24 12
.
.
2015 1 1 1
2015 2 1 1
.
.
2015 365 12 24
我可以用这个生成月份:
library(dplyr)
months <- list(1:31, 32:59, 60:90, 91:120, 121:151, 152:181, 182:212, 213:243, 244:273, 274:304, 305:334, 335:365)
df1 <- df %>% group_by(year) %>%
mutate(month = sapply(day, function(x) which(sapply(months, function(y) x %in% y)))
但是我不知道15天的期限是怎么产生的?
为了处理不应包括闰年的 2 月 29 日的问题,我们可能会生成一个完整的日期序列,然后删除 2 月 29 日的实例。从日期中获取 month
。通过检查 %d
是否为 <= 15
并从 2*
中减去月份数来计算 two-week 周期。
# complete sequence of dates
# use two years in this example, with 2012 being a leap year
dates <- data.frame(date = seq(as.Date("2011-01-01"), as.Date("2012-12-31"), by = "1 day"))
# remove Feb 29th in leap years
d <- dates[format(dates$date, "%m-%d") != "02-29", , drop = FALSE]
# create month
d$month <- month(d$date)
# create two-week number
d$twoweek <- d$month * 2 - (as.numeric(format(d$date, "%d")) <= 15)