我在 R 中有一系列日期,对于每个日期,我需要获取年、月和日。我尝试使用 strftime 函数打印出年份,但 R 的行为非常奇怪。此代码失败:
# 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)
}
确切的错误信息是:Error in as.POSIXlt.numeric(x, tz = tz) : 'origin' must be supplied
另一方面,这段代码没有任何错误:
# 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)
}
为什么第一个示例失败而第二个示例有效?我怀疑在第一个示例中 R 试图将我的日期转换为某种 POSIXct 对象,而在第二个示例中它没有?我很困惑为什么会有任何差异,我希望能解释一下发生了什么。我正在使用 R 版本 3.2.2。