Yes, you should definitely use the second approach: if you do the first, you are considering distant observations as close. If auto-correlation is decreasing with the lag (as is usually the case) then this would lead to an under-estimation of the ACF values: indeed, using say lag 5 (low correlation) for estimating lag 1 (higher correlation) biases your results. See the plot below to see this result.
Also, no need to fill-in manually NA, as acf()
is calling as.ts()
, and as.ts()
on a zoo
object returns a vector with NA already.
library(zoo)
#>
#> Attaching package: 'zoo'
#> The following objects are masked from 'package:base':
#>
#> as.Date, as.Date.numeric
N <- 5000
x <- arima.sim(model = list(ma = c(0.2, 0.9)), n = N)
set.seed(123)
index_x <- sort(sample(1:N, size = N/5, replace = FALSE))
x_miss <- x[index_x]
x_miss_zoo <- zoo(x_miss, order.by = index_x)
## coredata
ac_1 <- acf(coredata(x_miss_zoo), lag.max = 24, plot = FALSE)
ac_2 <- acf(x_miss_zoo, na.action = na.pass, lag.max = 24, plot = FALSE)
library(tidyverse)
data_frame(lag = 0:24,
acf_coredata = ac_1$acf[,1,],
acf_na_pass = ac_2$acf[,1,]) %>%
gather(method, value, -lag) %>%
mutate(lag = ifelse(method =="acf_coredata", lag, lag +0.5)) %>% #kind of a hack...
ggplot(aes(x = lag, y= value, colour = method)) +
geom_segment(aes(xend = lag, yend = 0)) +
ggtitle("ACF with the 2 methods, true should be l1= 0.2, l2 = 0.9")
Created on 2018-11-16 by the reprex package (v0.2.1)