How to flag last friday or last day or month

前端 未结 4 579
慢半拍i
慢半拍i 2021-01-22 17:53

I have a data frame of dates and the day of the week

> head(data)
         day   weekday
1 2016-01-01    Friday
4 2016-01-04    Monday
5 2016-01-05   Tuesday
         


        
4条回答
  •  一整个雨季
    2021-01-22 17:56

    require(data.table)
    
    lfom<-function(d){
      x<-seq(min(d),max(d),by=1)
      fri<-which(wday(x)==6)
      mend<-which(mday(x)==1)-1
      d %in%  x[fri[findInterval(mend,fri)]]
    }
    
    ldom<-function(d){
      x<-seq(min(d),max(d),by=1)
      mend<-which(mday(x)==1)-1
      d %in%  x[mend]
    }
    
    
    data <-data.frame(
      day = seq(as.Date("2014-01-01"), as.Date("2016-05-10"), "day"), 
      weekday = weekdays(seq(as.Date("2014-01-01"), as.Date("2016-05-10"), "day"))
    )
    excludeDays <- c("Saturday", "Sunday")
    data <- data.table(subset(data, !weekdays(data$day) %in% excludeDays)) #exclude weekend
    data$lfom<-lfom(data$day)
    data$ldom<-ldom(data$day)
    

提交回复
热议问题