Reputation: 399
I'm working with a small, simple matrix in R to show the comparison between using the (cov)
function and the mathematical computation of the variance-covariance matrix using the formula as (1/n-1) * (t(x) %*% as.matrix(x) - n %*% Ybar * (t(Ybar)
here is the data I'm working with for reference:
> dput(x)
structure(c(1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L, 1L,
2L, 3L, 4L, 5L, 6L), .Dim = c(6L, 3L))
When I run x.cov <- cov(x)
it returns a 3 x 3 matrix with all values = 3.5
The code below is what I'm using to obtain the variance-covariance matrix using computational formula, but it is returning an error stating "in t(x) %% as.matrix(x) - 6 %% x.meanvec %*% t(x.meanvec) : non-conformable arrays"
one <- rep(1, 6)
x.meanvec <- (1/6) * t(one) %*% as.matrix(x)
matrix.t <- (1/5) * (t(x) %*% as.matrix(x) - 6 %*% x.meanvec %*% t(x.meanvec))
How can I fix the formula to avoid this error?
Upvotes: 0
Views: 155
Reputation: 132576
I don't understand your formula and don't believe it is correct.
I'd do this:
(1/5) * (t(x - one %*% x.meanvec) %*% (x - one %*% x.meanvec))
Or more efficiently:
1/5 * crossprod(x - one %*% x.meanvec)
Upvotes: 1