[R] loop with dates

Jagat.K.Sheth at wellsfargo.com Jagat.K.Sheth at wellsfargo.com
Fri Dec 12 20:40:54 CET 2008


 

> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Fernando Bizuet
> Sent: Friday, December 12, 2008 12:55 PM
> To: r-help at r-project.org
> Subject: [R] loop with dates
> 
> Hello,
> 
> I am trying to do a loop with dates, but when I try to use 
> the index is not
> a date.

See ?"for". That help page mentions the following which can clarify what
to expect 

"... The variable 'var' has the same type as 'seq' ..."

Small illustration,

fac  <- gl(5,1,labels=letters[1:5])
fac
[1] a b c d e
Levels: a b c d e

typeof(fac)
[1] "integer"

for(i in fac) print(i)
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5


> 
>    Fcorte <-  as.Date('2008/11/30',format = "%Y/%m/%d")
>    fini <- Fcorte + 1
>    ffin <- seq(fini,by='months',length=2)[2] - 1
> 
>    for (i in seq(fini,to = ffin, by='days'))
>     print (weekdays(i))  # i doesn't a date

typeof(ffin)
[1] "double"

As your index is no longer of class 'Date', you will get
Error in UseMethod("weekdays") : no applicable method for "weekdays

> 
> How can I do a loop with dates and get the index of each 
> date? are there a
> method to convert the index i to date?

Here's one way 
dd <- seq(fini,to = ffin, by='days')
for (i in seq_along(dd)) print(dd[i])

> 
> 
> Thanks in advance.
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> 



More information about the R-help mailing list