我有以下功能。 CreateChronVector
確實如此。默認情況下,結果矢量每小時一次。函數將小時向量四捨五入到小時。如何創建時間記錄均勻分佈的時鐘序列(一致的delta t)
CreateChronVector <- function(chronFrom, chronTo, frequency = "hourly") {
library(chron)
datesFrom <- dates(chronFrom)
timesFrom <- (chronFrom - dates(chronFrom))
datesTo <- dates(chronTo)
timesTo <- (chronTo - dates(chronTo))
if ((timesFrom != 0 || timesTo != 0) && frequency == "daily") {
print("Error: The indicated dates have hour components while the given frequency is daily.")
}
else {
if (timesTo == 0 && frequency == "hourly") {
timesTo <- 23/24
}
if (frequency == "hourly") {
chronFrom <- chron(dates = datesFrom, times = timesFrom,
format = c(dates = "m/d/y", times = "h:m:s"))
chronTo <- chron(dates = datesTo, times = timesTo,
format = c(dates = "m/d/y", times = "h:m:s"))
dateVector <- seq(chronFrom, chronTo, by = 1/24)
}
else if (frequency == "daily") {
dateVector <- seq(datesFrom, datesTo)
}
return(dateVector)
}
}
RoundHour <- function(x) {
res <- trunc(x,'hours', eps=1e-17)
res <- ifelse((x-res) > 0.5/24, res+1/24, res)
return(as.chron(res))
}
我面臨的問題是間隔不一致。作爲一個例子,下面的代碼返回兩個不同的間隔尺寸:
unique(diff(CreateChronVector(as.chron('2010-01-01'), as.chron('2010-01-01'))))
同樣的,用我的舍入函數不能解決問題:
unique(diff(RoundHour(CreateChronVector(as.chron('2010-01-01'), as.chron('2010-01-01')))))
我敢肯定,這個問題有圓做關閉錯誤。我一直在嘗試使用trunc函數和它的eps參數,但沒有運氣。
'chron'使用浮點,所以你不能真正期望間隔是完全相同的。間隔長度之間的差異可以忽略不計,應該足夠好。 – 2013-02-25 23:32:12
你需要使用chron嗎?在xts中,您可以非常輕鬆地完成所有操作。 – 2013-02-26 03:56:01
感謝xts @geektrader的建議。我只是印了小插曲。看起來很有希望! – JAponte 2013-02-27 16:59:20