0

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.

jirikadlec2
  • 1,256
  • 1
  • 23
  • 36

1 Answers1

2

The for is creating d as numeric. Here are two approaches.

Below the comments were removed and only the code lines marked ## have been changed.

1) list Use a list like this:

dates <- seq(as.Date("1987-03-29"), as.Date("1991-12-31"), by=1)

for (d in as.list(dates)) {  ##
  year <- strftime(d, "%Y")
  print(year)
}

2) as.Date or convert d back to "Date" class.

dates <- seq(as.Date("1987-03-29"), as.Date("1991-12-31"), by=1)

for (d in dates) {
  year <- strftime(as.Date(d, origin = "1970-01-01"), "%Y") ##
  print(year)
}
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • interesting ... So that's why when I do `for (d in dates) { print(d) }` i 'm getting numbers like 8033, 8034, ... – jirikadlec2 Dec 03 '15 at 00:17