【问题标题】:rbind.zoo(...) : indexes overlap Errorrbind.zoo(...) : 索引重叠错误
【发布时间】: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 &lt;- ave(x, as.Date(index(x)), FUN= function(x) {xv &lt;- as.vector(x);as.xts(ifelse(xv == -Inf,NA,xv),index(x))})。还要注意使用ifelse 进行从-InfNA 的转换。

标签: r aggregate xts zoo


【解决方案1】:

这里没有理由按天分组,因为无论如何计算都是逐个元素完成的:

replace(x, x == -Inf, NA)

或者如果覆盖是可以的,那么:

x[x == -Inf] <- NA

如果您的实际函数确实使用了分组并且这只是一个示例,那么将 ave 应用于 coredata(x) 以便我们处理普通向量并确保应用的函数实际返回结果(在质疑它没有):

fun <- function(x) replace(x, x == -Inf, NA)
x[] <- ave(coredata(x), as.Date(index(x)), FUN = fun)

我们也可以考虑使用!is.finite(x) 进行测试。

【讨论】:

    【解决方案2】:

    现有的答案很好,但您也可以使用xts 工具(将zoo 转换为xts)轻松地在时间间隔(小时、周天等)内轻松简洁地实现平均(或任何合理的函数) .你知道?period.apply,以及它的包装函数apply.daily吗?

    # Solve your overall problem in one line with no error generated when Inf values included:
    x.daily <- apply.daily(x, mean, na.rm = T)
    
    # > x.daily
    # [,1]
    # 2010-01-05 00:20:00 -Inf
    # 2010-01-06 00:08:00  NaN
    
    # Solve your first problem compactly (Replace +-Inf values in column 1 (generalise to any column number) of `x` with NA):
    x[!is.finite(x[, 1]) &!is.na(x[, 1]), 1] <- NA
    
    # Solve your second problem compactly (average by day):
    x.daily <- apply.daily(x, FUN = mean, na.rm = T)
    
    #Optional: tidy up timestamps in x.daily for equal spaced alignment in YYMMDD HHMMSS (NB HHMMSS will vary depending on your timezone.  Should align for 86400 to 00:00:00 equivalent in UTC):
    x.daily <- align.time(x.daily, 86400)
    # > x.daily
    # [,1]
    # 2010-01-05 19:00:00    2
    # 2010-01-06 19:00:00  NaN
    

    【讨论】:

    • 是的,我知道period.apply 函数,但是根据this S.O 帖子将它们与 na.locf 函数一起使用时存在问题,所以我改用 ave 函数.
    • 如果您使用split(..., "days")),然后将lapply 与您想要的聚合一起使用(此处为mean),然后对结果进行rbind,则可以轻松避免该“问题”。
    猜你喜欢
    • 2023-04-09
    • 1970-01-01
    • 2019-10-23
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 2011-01-25
    • 2020-05-27
    • 2017-01-06
    相关资源
    最近更新 更多