Resolving discrepancy in covariance function calculated manually vs in R?

Viewed 80

I am trying to evaluate the following formula in R

enter image description here
where, ni is the number of individuals on patch i, m is the mean of ni and N is the total number of individuals.

However, when I manually calculate the values vs. calculating it using the covariance function in R, it produces two different answers. I am wondering what the discrepancy is and if someone could suggest if I'm using the incorrect covariance function, or anything else obvious that I'm missing.

nx <- c(1,0,3,2)
ny <- c(3,1,0,1)

mx <- mean(nx)
my <- mean(ny)


Nx <- sum(nx)


covxy.manual <- ((sum(nx * ny)/Nx) - my) * my
covxy.manual # Answer: -0.520

covxy.direct <- cov(nx,ny)/(mx * my)
covxy.direct # Answer: -0.444

As per suggestion, I tried spearmann correlation on a different set, but that doesn't match up either

nx <- c(3,0,3,3)
ny <- c(1,0,1,1)

mx <- mean(nx)
my <- mean(ny)
Nx <- length(nx)

covxy.manual <- ((sum(nx * ny)/(mx * Nx)) - my) * my
covxy.manual 

covxy.manual <- ((sum(nx * ny)/(mx * Nx)) - my) * my
covxy.manual 

Nx <- sum(nx)
covxy.manual <- ((sum(nx * ny)/Nx) - my) * my
covxy.manual #Answer: 0.1875


covxy.direct <- cov(nx,ny, method = "spearman")/(mx * my)
covxy.direct #Answer: 0.592
0 Answers
Related