【发布时间】:2016-10-26 13:06:40
【问题描述】:
我正在尝试将函数应用于 xts 对象。我正在使用ave 函数将该函数分别应用于每一天。该函数抛出以下错误:
Error in rbind.zoo(...) : indexes overlap In addition: Warning messages:
1: In split.default(seq_len(nrow(xc)), f, drop = drop, ...) :
data length is not a multiple of split variable
2: In zoo(value2, i2) :
some methods for “zoo” objects do not work if the index entries in ‘order.by’ are not unique
我已经调试了该函数,当我尝试使用以下行将-Inf 转换为NA 时,它会抛出错误:x[x == -Inf] <- NA。
这是一个通过ave 函数仅应用函数有问题的行的最小可重现示例:
x <- as.xts(c(NA,-Inf,1,2,3,-Inf,NA,NA,NA),as.POSIXct(c(
"2010-01-05 00:00:00", "2010-01-05 00:04:00", "2010-01-05 00:08:00",
"2010-01-05 00:12:00", "2010-01-05 00:16:00", "2010-01-05 00:20:00",
"2010-01-06 00:00:00", "2010-01-06 00:04:00", "2010-01-06 00:08:00")))
out <- ave(x, as.Date(index(x)), FUN= function(x) x[x == -Inf] <- NA)
【问题讨论】:
-
为避免该错误,您可以在函数内先将
x转换为向量,然后返回as.xts:out <- ave(x, as.Date(index(x)), FUN= function(x) {xv <- as.vector(x);as.xts(ifelse(xv == -Inf,NA,xv),index(x))})。还要注意使用ifelse进行从-Inf到NA的转换。