生成一天中属于哪个15天的时间段

编程入门 行业动态 更新时间:2024-10-24 12:20:29
本文介绍了生成一天中属于哪个15天的时间段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个年份和日期的数据框

I have a data frame with year and day

df <- data.frame(year = rep(1980:2015,each = 365), day = 1:365)

请注意,我一年仅需要365天,也就是说我每天都在 365年.

Please note that I only need 365 days a year i.e. I am asusming each day has 365 years.

我想生成两个数据: 1)每天属于哪个月份 2)每天属于15天的期限.一年将有24个15天的期限.即每个月将分成两半;

I want to generate two data: 1) which month does each day fall in 2) which 15-days period each day fall in. A year will have 24 15-days period. i.e. each month will be split into two halves something like this;

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

我的最终数据应该像这样

My final data should look like this

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

我可以使用以下方法生成月份:

I can generate the month using this:

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天期限?

But I do not know how to generate the 15-days period?

推荐答案

要处理不包括leap年2月29日的情况,我们可以生成完整的日期序列,然后删除2月29日的实例.从日期开始抓取month.通过检查月份%d是否为<= 15并从2*减去月份数来计算两周时间.

To handle that Feb 29th in leap years should not be included, we may generate a complete sequence of dates and then remove instances of Feb 29th. Grab month from the date. Calculate the two-week periods by checking if day of the month %d is <= 15 and subtract from 2* the month number.

# 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)

更多推荐

生成一天中属于哪个15天的时间段

本文发布于:2023-10-24 08:41:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1523468.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时间段

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!