Hi supposed I have a vector consisting of 0's and 1's; will the default acf function be able to calculate this correctly?
set.seed ( 12 )
bin = sample(c(0,1), replace=TRUE, size=5000)
acf (bin )
CodePudding user response:
Yes. Your example doesn't work because it is completely random. But we can create a binomial sample with an oscillating probability of 1s and 0s like this:
times <- seq(0, 20 * pi, pi / 6)
probs <- sin(times) * 0.5 0.5
Our probability of getting a 1 at each time step looks like this:
plot(times, probs, type = "l")
And we can generate a sample like this:
set.seed(1)
samp <- rbinom(length(times), 1, probs)
samp
#> [1] 0 1 1 1 1 1 0 1 0 0 0 0 0 1 1 1 1 0 1 0 1 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0
#> [38] 1 1 1 1 0 0 1 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 1 1
#> [75] 1 1 1 1 1 0 0 0 0 1 0 0 1 1 1 1 0 1 0 0 0 1 0 1 1 1 1 0 1 0 0 0 0 0 0 1 1
#> [112] 1 1 0 0 0 0 0 0 0 1
And we can demonstrate that acf
correctly identifies the autocorrelation:
acf(samp)
Created on 2022-02-12 by the reprex package (v2.0.1)