On Mar 9, 2013, at 9:24 AM, Alexandre Sieira wrote: > I understand that the two following loops should produce the exact same > output. However, they do not. It appears that looping directly through the > sequence of Date objects somehow makes them be coerced to numeric: > >> date1 = "20130301" >> date2 = "20130302" >> >> d1 = as.Date(date1, format="%Y%m%d", tz="GMT") >> d2 = as.Date(date2, format="%Y%m%d", tz="GMT") >> >> range = seq(from=d1, to=d2, by="day") >> for (i in 1:length(range)) print(class(range[i])) > > [1] "Date" > [1] "Date" >> >> for (i in seq(from=d1, to=d2, by="day")) print(class(i)) > [1] "numeric" > [1] "numeric" > > This is output from R version 2.15.2 (2012-10-26) on Mac OS X 10.8.2. > > Is this expected behavior?
It wasn't expected by me either, but it is what both my Mac R 2.15.3 and my Windows(32bit) 2.15.1 display. If you put those dates in a list, you do not get the coercion: > for (i in list(d1,d2)) print(class(i)) [1] "Date" [1] "Date" I was unable to find the reason for the original coercion in the help("for") page or the R Language Definition entry regarding for-loops. On the hunch that coercion via as.vector might be occurring, I tried with with a factor vector and did see that it was coerced to "character" which is the behavior that would be expected if that were happening behind the scenes: ff <- factor(letters[1:3]) as.vector(ff) #[1] "a" "b" "c" for (i in ff) print(class(i)) #[1] "character" #[1] "character" #[1] "character" (I also tried searching for loop in the R Internals document and found nothing that explained this to me.) -- David. > -- > Alexandre Sieira > CISA, CISSP, ISO 27001 Lead Auditor > > "The truth is rarely pure and never simple." > Oscar Wilde, The Importance of Being Earnest, 1895, Act I > > > Sent with Sparrow (http://www.sparrowmailapp.com/?sig) > > ______________________________________________ > R-help@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. David Winsemius Alameda, CA, USA ______________________________________________ R-help@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.