[R] working with weekdays

Gavin Simpson gavin.simpson at ucl.ac.uk
Mon Feb 18 14:59:39 CET 2008


On Mon, 2008-02-18 at 12:56 +0000, lamack lamack wrote:
> 
> Dear all, is it possible create, automatically, a variable with all the
> Monday and Thursday?
> 
> 18/02/2008
> 21/02/2008
> 25/02/2008
> 28/02/2008
> 03/03/2008
> .
> .
> for all months

Here is one way (for all months in 2008), if you know the first
Monday/Thursday

> first.mon <- as.Date("07-01-2008", format = "%d-%m-%Y")
> first.thu <- as.Date("03-01-2008", format = "%d-%m-%Y")
> mondays <- seq(from = first.mon, by = "weeks", length = 52)
> thursdays <- seq(from = first.thu, by = "weeks", length = 52)
> sort(c(mondays, thursdays))
  [1] "2008-01-03" "2008-01-07" "2008-01-10" "2008-01-14" "2008-01-17"
  [6] "2008-01-21".....

And one if you don't:

> days <- seq(as.Date("01-01-2008", format = "%d-%m-%Y"), 
              as.Date("31-12-2008", format = "%d-%m-%Y"), by = "days") 
> monthu <- days[format(days, format = "%w") %in% c(1,4)]
> all.equal(monthu, sort(c(mondays, thursdays)))
[1] TRUE

HTH

G

-- 
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
 Dr. Gavin Simpson             [t] +44 (0)20 7679 0522
 ECRC, UCL Geography,          [f] +44 (0)20 7679 0565
 Pearson Building,             [e] gavin.simpsonATNOSPAMucl.ac.uk
 Gower Street, London          [w] http://www.ucl.ac.uk/~ucfagls/
 UK. WC1E 6BT.                 [w] http://www.freshwaters.org.uk
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%



More information about the R-help mailing list