2016-03-15 63 views
1

似乎lapply軋液機POSIXlt記錄:爲什麼lapply mangle POSIXlt?

> hours 
[1] "2016-01-01 00:00:00 GMT" "2016-01-01 01:00:00 GMT" "2016-01-01 02:00:00 GMT" 
> str(hours) 
POSIXlt[1:3], format: "2016-01-01 00:00:00" "2016-01-01 01:00:00" "2016-01-01 02:00:00" 
> dput(hours) 
structure(list(sec = c(0, 0, 0), min = c(0L, 0L, 0L), hour = 0:2, 
    mday = c(1L, 1L, 1L), mon = c(0L, 0L, 0L), year = c(116L, 
    116L, 116L), wday = c(5L, 5L, 5L), yday = c(0L, 0L, 0L), 
    isdst = c(0L, 0L, 0L)), .Names = c("sec", "min", "hour", 
"mday", "mon", "year", "wday", "yday", "isdst"), class = c("POSIXlt", 
"POSIXt"), tzone = "GMT") 
> read.csv(file.path(data.dir,strftime(hours[1],"%Y%d%m%H.csv"))) 
.... success .... 
> lapply(hours, function (h) read.csv(file.path(data.dir,strftime(h,"%Y%d%m%H.csv")))) 
Error in as.POSIXlt.numeric(x, tz = tz) (from #1) : 'origin' must be supplied 
Calls: lapply -> FUN -> read.csv -> read.table -> file.path -> strftime -> format -> as.POSIXlt -> as.POSIXlt.numeric 
> lapply(hours,function(h) { 
+ print(h) 
+ str(h) 
+ read.csv(file.path(data.dir,strftime(h,"%Y%m%d%H.csv"))) 
+ }) 
+ . + [1] 0 0 0 
num [1:3] 0 0 0 
Error in as.POSIXlt.numeric(x, tz = tz) (from #1) : 'origin' must be supplied 

IOW,在函數的hours元件內部lapply是數值向量,不POSIXlt

它看起來像hours是個人POSIXlt字段的列表,而不是一個向量或POSIXlt對象。

我做錯了什麼?

PS。下面似乎是一個解決方法:

lapply(1:length(hours),function(i) ....hours[i]...) 

回答

4

POSIXlt對象是矢量(見?POSIXlt)的命名列表。 lapply在列表上循環並在每個向量上調用FUN"sec","min",...,"isdst")。

這與data.frame對象的向量列表類似,因此lapply在data.frame的列上循環,並在每個向量上調用FUN

更好的解決辦法是將您的POSIXlt對象轉換爲POSIXct,除非您需要POSIXlt中的特定功能。