sbg
sbg

Reputation: 1772

How to calculate autocorrelation in r (zoo object)

I am trying to check for auto-correlation in a zoo object (monthly data with several columns) using:

acf(jan, plot=F)$acf[2]

but I get the following error:

Error in na.fail.default(as.ts(x)) : missing values in object

To simplify, I extracted just one of the columns which I called "a" (so now I have a simple zoo object with index and data), and used:

acf(a)

but still get the same error. Can't acf be used in zoo objects?

Upvotes: 10

Views: 25932

Answers (4)

soroso
soroso

Reputation: 11

I had the same problem as you when trying to use the ACF function on monthly S&P returns. Turns out the coredata function solved the problem as it stripped date information from returns in my data set from yahoo finance.

you might want to give it a shot!

Upvotes: 1

Cookie
Cookie

Reputation: 12662

Or self made

autocorrplot <- function(x)
{
  n <- length(x)
  barplot(sapply(1:10,function(i) cor(x[-i:-1],x[(-n-1+i):-n])))
}

Upvotes: 0

Dr G
Dr G

Reputation: 4017

Just use

acf(coredata(jan))

That should work fine. Keep in mind that you have to provide a regularly spaced time series for that to give you a meaningful answer.

Upvotes: 11

Brandon Bertelsen
Brandon Bertelsen

Reputation: 44648

The default behaviour for acf is na.action = na.fail. Try setting it to na.omit or na.pass in your call acf(..., na.action = na.omit)

Upvotes: 4

Related Questions