R 生成一天中的15天周期
我有一个带有年份和日期的数据框R 生成一天中的15天周期,r,dplyr,as.date,R,Dplyr,As.date,我有一个带有年份和日期的数据框 df <- data.frame(year = rep(1980:2015,each = 365), day = 1:365) 我的最终数据应该是这样的 Year Day Quarter Month 1980 1 1 1 1980 2 1 1 . . 1980 365 24 12
df <- data.frame(year = rep(1980:2015,each = 365), day = 1:365)
我的最终数据应该是这样的
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)))
库(dplyr)
月份%
突变(月=sappy(天,函数(x))其中(sappy(月,函数(y)x%在%y中)))
但是我不知道如何生成15天周期?要处理闰年中不应包含2月29日的问题,我们可以生成一个完整的日期序列,然后删除2月29日的实例。从日期开始抓取
月份。通过检查该月的日期%d
是否为您的dplyr
code为月份生成29天2月和30天12月。@谢谢你指出。我如何修复它?首先创建一个列表:months我很抱歉Henrik。我刚意识到当我运行上述函数时,2016年12月只有30天。你能再检查一下吗?我想问题是我把所有的日子都当作365天因为您的函数将2016年视为闰年,从12月到2月需要一天的时间才能使其成为闰年。我必须从闰年中删除2月29日,即所有年份中的2月应该只有28天。
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)))
# 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)