Asher11
Asher11

Reputation: 1325

covariance formula: multiplying just the weights "in couple" in R

ok basically if you look at the covariance formula when weights are involved (look at this picture so everything is clear http://postimg.org/image/sjr2tnk85/), I just want to calculate the sum of all the different couples of weights as highlighted in the link of the picture I uploaded.

I absolutely need that specific quantity highlighted in the picture. I have no use of the formulas cor() [i tried but it was useless]

I have tried to use "for" loops trying to following the mathematical formula but came out empty handed.

I am sorry if this post lacks the specificity required for this forum but it was the best way I could think of in order to explain my problem.

Upvotes: 0

Views: 211

Answers (1)

Neal Fultz
Neal Fultz

Reputation: 9687

sum(outer(w,w), -crossprod(w)) / 2

Z <- outer(a,b) creates a matrix where Z[i,j] = a[i]*b[j]. Plugging in w for both a and b, this is a symmetric matrix.

crossprod(x) calculates the sums of squares of x. This is the sum of the diagonals of the above matrix.

Take the difference, then divide by two because you only want the top half of the matrix.

Alternatively, you could try sum( apply(combn(w,2), 2, prod) ) to explicitly form each pair, multiply them, and sum them up.

Upvotes: 1

Related Questions