Fill in the vector only on weekdays

I know the start date of start and the last maturity date. How can I fill in a vector with dates excluding holidays? For example, say:

 > start = as.Date("2013-02-28"); > maturity = as.Date("2013-03-07"); 

I would like to get the following vector as a result:

 results [1] "2013-03-01" "2013-03-04" "2013-03-05" "2013-03-06" "2013-03-07" > start = as.Date("2013-02-28"); > maturity = as.Date("2013-03-07"); > x <- seq(start,maturity,by = 1) > x [1] "2013-02-28" "2013-03-01" "2013-03-02" "2013-03-03" "2013-03-04" "2013-03-05" [7] "2013-03-06" "2013-03-07" > x <- x[!weekdays(x) %in% c('Saturday','Sunday')] > x [1] "2013-02-28" "2013-03-01" "2013-03-02" "2013-03-03" "2013-03-04" "2013-03-05" [7] "2013-03-06" "2013-03-07" 

The same results ...?

+4
source share
2 answers

There are probably a billion ways to do this with many functions from multiple packages. But my first thought is to just make a sequence and then delete the weekend:

 x <- seq(as.Date('2011-01-01'),as.Date('2011-12-31'),by = 1) x <- x[!weekdays(x) %in% c('Saturday','Sunday')] 

This answer is only valid with the English system. For example, in the French version, "Saturday" and "Sunday" should be translated into "samedi" and "dimanche"

+7
source

This is less humane than @joran's answer :), but it does not depend on local time

 dd <- seq(as.Date('2011-01-01'),as.Date('2011-12-31'),by = 1) dd[! (as.POSIXlt(dd)$wd %in% c(0,1))] 

PS: another option is to set the locales before applying weekdays

 tt <- Sys.getlocale('LC_TIME') Sys.setlocale('LC_TIME','ENGLISH') dd <- dd[!weekdays(x) %in% c('Saturday','Sunday')] Sys.setlocale('LC_TIME',tt) 
+3
source

All Articles