Start sequence on Monday, end on Friday

Given random start and end dates, how can I create a new sequence (or change it) to start on the first Monday and finish last Friday?

MyDays <- seq(StartDate , EndDate , by = "day")
SequenceDay <- days [!is.weekend(MyDays)]

Thank!

+3
source share
3 answers

Like Tony Braial. Remember that they only work if your system uses English words for the days of the week.

StartDate <- as.Date("2010-01-01")
EndDate <- as.Date("2010-12-31")
myDays <- seq(StartDate , EndDate, by = "day") 
excludeDays <- c("Saturday", "Sunday")
myWeekDays <- subset(myDays, !weekdays(myDays) %in% excludeDays)
firstMonday <- which(weekdays(head(myWeekDays, 5)) == "Monday")
lastFriday <- length(myWeekDays) - 5 + 
              which(weekdays(tail(myWeekDays, 5)) == "Friday")
myCompleteWeeks <- myWeekDays[firstMonday:lastFriday]
+3
source

POSIXlt provides you with a language-independent way. match()and rev()make a little easier comparison. The package chroncontains a function is.weekend(). Using the myDays of Winchester vector:

myDays <- as.POSIXlt(myDays)
wdays <- myDays$wday
n <- length(myDays)+1

myDays <- myDays[match(1,wdays):(n-match(5,rev(wdays)))]

To exclude weekends, you can use the chron library

library(chron)
myDays[!is.weekend(myDays)]

POSIXt, Date chron, . POSIXlt % in%:

myDays[! myDays$wday %in% c(0,6)]
+3

Assuming that I understood correctly ("at the moment the end of the working day, and I'm in the pub"), then what about this:

# set start and end dates
n <- 31
d.start <- Sys.Date()
d.end <- d.start + n

# workhorse code
my.seq = seq(d.start, d.end, "days")
x1 <- weekdays(my.seq)
first.Mon <- which(x1=="Monday")[1]
last.friday <- which(x1=="Friday")[length(which(x1=="Friday"))]
x <- my.seq[first.Mon:last.Fri]
ind.sats <- which(weekdays(x) == "Saturday")
ind.suns <- which(weekdays(x) == "Sunday")
x <- x[-c(ind.sats, ind.suns)]

What should give you:

> x
 [1] "2011-03-07" "2011-03-08" "2011-03-09" "2011-03-10" "2011-03-11"
 [6] "2011-03-14" "2011-03-15" "2011-03-16" "2011-03-17" "2011-03-18"
[11] "2011-03-21" "2011-03-22" "2011-03-23" "2011-03-24" "2011-03-25"
[16] "2011-03-28" "2011-03-29" "2011-03-30" "2011-03-31" "2011-04-01"

or

> weekdays(x)
 [1] "Monday"    "Tuesday"   "Wednesday" "Thursday"  "Friday"    "Monday"   
 [7] "Tuesday"   "Wednesday" "Thursday"  "Friday"    "Monday"    "Tuesday"  
[13] "Wednesday" "Thursday"  "Friday"    "Monday"    "Tuesday"   "Wednesday"
[19] "Thursday"  "Friday"

Depending on what you like. In any case, this is the main idea, you probably need to add some error checking.

+2
source

Source: https://habr.com/ru/post/1795585/


All Articles