# [R] ccf and covariance

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Apr 23 20:31:24 CEST 2008

```On Wed, 23 Apr 2008, Bob Farmer wrote:

> Hi.
> It's my understanding that a cross-correlation function of vectors x
> and y at lag zero is equivalent to their correlation (or covariance,
> depending on how the ccf is defined).

The ratio of your values is

> MASS::fractions(282568.5/259021)
[1] 12/11

?  Do you recognize it?

There is an explanation in MASS4, p. 390, for example.

> If this is true, could somebody please explain why I get an
> inconsistent result between cov() and ccf(type = "covariance"), but a
> consistent result between cor() and ccf(type = "correlation")?
> Or have I misunderstood what is a cross-correlation?
> (unfortunately, I can't seem to get a look at the ccf code, since I
> think it's buried in some C function outside of the main environment)

It is in the R sources, not 'buried' at all - that is what 'Open Source'
means. You can browse them at https://svn.r-project.org/R/trunk, or

> Thanks very much.
> --Bob Farmer
> PhD candidate, Dalhousie University
>
> Example:
> d1<-data.frame(matrix(ldeaths, nrow = 6, byrow = T))
> seventy_4<-as.numeric(d1[1,])
> seventy_5<-as.numeric(d1[2,])
>
> ccf(x=seventy_4, y=seventy_5,
>  plot = F, lag.max = 0, type = "covariance"
> )
> cov(seventy_4, seventy_5)  #inconsistent
>
> ccf(x=seventy_4, y=seventy_5,
>  plot = F, lag.max = 0, type = "correlation"
> )
> cor(seventy_4, seventy_5)  #consistent
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> and provide commented, minimal, self-contained, reproducible code.
>

--
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

```