0
votes

I have trouble with an error in zoo, using the lag.zoo function

Error in rbind.zoo(...) : indexes overlap Warning: In zoo(rval[i], index(x)[i]) : some methods for “zoo” objects do not work if the index entries in ‘order.by’ are not unique

t1<-c("21.04.2019 20:00:00","21.04.2019 20:01:00","21.04.2019 20:02:00","21.04.2019 20:03:00","21.04.2019 20:04:00","21.04.2019 20:05:00","21.04.2019 20:06:00","21.04.2019 20:07:00","21.04.2019 20:08:00","21.04.2019 20:09:00","21.04.2019 20:10:00","21.04.2019 20:11:00")

v1<-c(15,15,15,14,15,14,15,14,15,15,15,14)

z1<-zoo(v1, as.POSIXct(strptime((t1), "%d.%m.%Y %H:%M:%S")))

head(lag(z1[,1], 2))

Using k=1 gives back the original time without lag (and no error and warning)

1
Try head(stats::lag(z1[,1], 2)), there are some 'genious' packages out there that mask the lag function. - jay.sf

1 Answers

0
votes

There are several problems:

  • Perhaps dplyr is loaded. It clobbers lag from the base of R so that no other packages can use it. When you load dplyr do it like this:

    library(dplyr, exclude = c("lag", "filter"))
    

    If you need to use dplyr's lag then refer to it as dplyr::lag . Although the above is probably the best way to handle this to avoid errors, if you already have dplyr loaded so that it is too late you can:

    1. detach it, detach("package:dplyr", unload = TRUE), or
    2. use stats::lag to refer to the lag generic in the base R which in turn will dispatch lag.zoo since zoo works consistently with it or
    3. enter lag <- stats::lag and then use lag as usual and use dplyr::lag if you need that version.
  • z1 is a vector zoo object, not a matrix zoo object so it does not really make sense to refer to its first column. It has no columns. Omit the [, 1] .

  • you probably meant -2, not +2. zoo uses the same convention as R itself which is that a lag of 2 refers to lagging the index, not the data, by 2. That is, a series lagged by 2 starts earlier whereas you likely want it to start later. See ?stats::lag for more on this. For example, below with a negative lag the 1st lag starts one position later and the 2nd lag starts 2 positions later.

    stats::lag(z1, -(0:2))
    
    ##                     lag0 lag-1 lag-2
    ## 2019-04-21 20:00:00   15    NA    NA
    ## 2019-04-21 20:01:00   15    15    NA
    ## 2019-04-21 20:02:00   15    15    15
    ## 2019-04-21 20:03:00   14    15    15
    ## 2019-04-21 20:04:00   15    14    15
    ## 2019-04-21 20:05:00   14    15    14
    ## 2019-04-21 20:06:00   15    14    15
    ## 2019-04-21 20:07:00   14    15    14
    ## 2019-04-21 20:08:00   15    14    15
    ## 2019-04-21 20:09:00   15    15    14
    ## 2019-04-21 20:10:00   15    15    15
    ## 2019-04-21 20:11:00   14    15    15