我有以下功能。 CreateChronVector
完全符合它的含义。默认情况下,生成的向量以小时为间隔。 RoundHour
函数将chron向量向上舍入到小时。
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参数,但没有运气。
答案 0 :(得分:0)
如果你试试the point from @G. Grothendieck,你可以看到他在说什么:
hours <- 1:23
dateVector <- sapply(hours , function(x){ chron( dates = "01/01/10" , times = paste0(x,":00:00") ) } )
head( dateVector )
[1] 14610.04166666666606034 14610.08333333333393966 14610.12500000000000000
[4] 14610.16666666666606034 14610.20833333333393966 14610.25000000000000000
unique(diff(dateVector))
[1] 0.04166666666787932626903 0.04166666666606033686548
所以你不能真正做到这一点,因为这些数字不能用浮点数来表示,但这对你来说有什么原因吗?
答案 1 :(得分:0)
您可以使用xts
包。在xts
对象中获得数据后,可以使用align.time
函数来“舍入”时间索引。在xts
PS:如果您提供可重复的数据示例,我将通过示例更新答案。