Looping over a Date or POSIXct object results in a numeric iterator

Viewed 15758

Why does iterating through a Date or POSIXct object result in numeric? For example:

test = as.Date("2009-01-01")
print( class( test ) )
# [1] "Date"
for ( day in test )
{
    print( class( day ) )
}
# [1] "numeric"

The same thing happens with POSIXct:

test = as.POSIXct("2009-01-01")
print( class( test ) )
# [1] "POSIXct" "POSIXt"
for ( day in test )
{
    print( class( day ) )
}
# [1] "numeric"
7 Answers

Not a solution per-se, but a useful trick when you want to check the dates in a loop:

for( i.date in as.character(Sys.Date()) ){ cat(paste("Date:", i.date, "\n")) }

just transform it as character beforehand. Most filters won't bother.

Related