Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
910 views
in Technique[技术] by (71.8m points)

r - Fill a vector with weekdays only

I know the start date start and the last date maturity. How can I fill in a vector with dates without taking weekends dates into account ? For instance, let's 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"

Same results... ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are probably a billion ways to do this with a variety of functions from multiple packages. But my first thought is to simply make a sequence and then remove the weekends:

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 valid only with an English based system. For instance, in a French version, 'Saturday' and 'Sunday' must be translated into 'samedi' and 'dimanche'


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...