生成每天15天的时间段

时间:2018-02-28 14:15:31

标签: r dplyr as.date

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

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天的时间?

1 个答案:

答案 0 :(得分:2)

为了处理闰年2月29日不应包括的内容,我们可能会生成完整的日期序列,然后删除2月29日的实例。从日期中抓取month。通过检查%d中某一天<= 152*并从# 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) 减去月份数来计算两周时段。

int FLAG_SEND=0;
int countMinute;
//...
//...
//...
if(countMinute>1){ //countMinute can be done in a various ways
    countMinute = 0;
    FLAG_SEND = 1;
}



if (sensorValue > 700){

    if(FLAG_SEND){
        digitalWrite(5, HIGH);
        if (client.publish(mqtt_topic, "**!!ALERT!!**")){
            Serial.println("Tripped and message sent!");
        } 
        else{
            Serial.println("Message failed to send. Reconnecting to MQTT Broker and trying again");
            client.connect(clientID);
            delay(10); // This delay ensures that client.publish doesn't clash with the client.connect call
            client.publish(mqtt_topic, "**!!ALERT!!**"); 
        }
        FLAG_SEND = 0;
    }
}