Jen Bohold
Jen Bohold

Reputation: 1068

Switch columns?

I have a variance-covariance matrix which looks like the following:

            hyperbPi       lZeta      lDelta
hyperbPi 0.005113433 0.009151182 0.008327188
lZeta    0.009151182 1.661749998 1.590549700
lDelta   0.008327188 1.590549700 1.526103143

How can I switch it in such a way that I have lZeta in the first column and hyperbPi in the second and lDelta in the third? I mean switching in such a way that the logic is not lost. I cannot just switch the column itself, because it is a variance-covariance matrix?

Upvotes: 0

Views: 166

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

Functions like cor, cov, and var will create a matrix in the same order as the columns in your source data.frame. You can easily specify another order with basic column indexing.

Consider this nonsense example:

set.seed(1)
x <- data.frame(matrix(sample(20, 18, replace = TRUE), ncol = 3))
names(x) <- c("two", "one", "three")
cov(x)
#              two   one     three
# two    36.666667 -25.8  4.866667
# one   -25.800000  45.9 -5.500000
# three   4.866667  -5.5 18.566667
cov(x[c(2, 1, 3)])
#         one        two     three
# one    45.9 -25.800000 -5.500000
# two   -25.8  36.666667  4.866667
# three  -5.5   4.866667 18.566667

Upvotes: 3

Related Questions