This is related to Looping over a Date or POSIXct object results in a numeric iterator
> dates <- as.Date(c("2013-01-01", "2013-01-02"))
> class(dates)
[1] "Date"
> for(d in dates) print(class(d))
[1] "numeric"
[1] "numeric"
I have two questions:
- What is the preferred way to iterate over a list of Date objects?
- I don’t understand Joshua’s answer (accepted answer from the question linked above), I’ll quote it here: "So your
Datevector is being coerced tonumericbecauseDateobjects aren’t strictly vectors". So how is it determined thatDateshould be coerced tonumeric?
There are two issues here. One is whether the input gets coerced from
Datetonumeric. The other is whether the output gets coerced tonumeric.Input
For loops coerce
Dateinputs tonumeric, because as @DWin and @JoshuaUlrich point out,forloops takevectors, andDates are technically not vectors.On the other hand,
lapplyand its simplifier offspringsapplyhave no such restrictions.Output
However! The output of
class()above is a character. If you try actually returning a date object,sapplyis not what you want.lapplydoes not coerce to a vector, butsapplydoes:That’s because
sapply‘s simplification function coerces output to a vector.Summary
So: If you have a
Dateobject and want to return a non-Dateobject, you can uselapplyorsapply. If you have a non-Dateobject, and want to return aDateobject, you can use aforloop orlapply. If you have aDateobject and want to return aDateobject, uselapply.Resources for learning more
If you want to dig deeper into vectors, you can start with John Cook’s notes, continue with the R Inferno, and continue with SDA.