I have a sequence of dates in R, and for each date I need to get the year, month, and day. I tried to use the strftime function to print out the year, but R behaves very strangely. This code fails:
# sequence of dates
dates <- seq(as.Date("1987-03-29"), as.Date("1991-12-31"), by=1)
# this fails with "'origin' must be supplied" error:
for (d in dates) {
year <- strftime(d, "%Y")
print(year)
}
The exact error message is: Error in as.POSIXlt.numeric(x, tz = tz) : 'origin' must be supplied
On the other hand, this code works without any error:
# sequence of dates
dates <- seq(as.Date("1987-03-29"), as.Date("1991-12-31"), by=1)
# this works
for (i in 1: length(dates)) {
year <- strftime(dates[i], "%Y")
print(year)
}
Why does the first example fail and the second example works? I suspect that in the first example R is trying to convert my date to some kind of POSIXct object and in the second example it doesn't? I'm confused why there's any difference and I'd appreciate an explanation of what's going on. I'm using R version 3.2.2.