Check correlation matrix
Is a given object a correlation matrix? This can be checked in three ways as follows:
### N is a correlation matrix
N <- diag(3)
check_correlation_matrix(N, dim = 3)
#> [1] TRUE
test_correlation_matrix(N, dim = 3)
#> [1] TRUE
assert_correlation_matrix(N, dim = 3)
### M is not a correlation matrix
M <- matrix(c(1, 0.9, 0.9, 0.9, 1, -0.9, 0.9, -0.9, 1), nrow = 3)
check_correlation_matrix(M)
#> [1] "Must have positive eigenvalues only"
test_correlation_matrix(M)
#> [1] FALSE
assert_correlation_matrix(M)
#> Error in eval(expr, envir, enclos): Assertion on 'M' failed: Must have positive eigenvalues only.
Check covariance matrix
The same checks for a correlation matrix also work for a covariance matrix:
### N is a covariance matrix
N <- diag(3)
check_covariance_matrix(N, dim = 3)
#> [1] TRUE
test_covariance_matrix(N, dim = 3)
#> [1] TRUE
assert_covariance_matrix(N, dim = 3)
### M is not a correlation matrix
M <- matrix(c(1, 2, 3, 2, 1, 2, 3, 2, 1), nrow = 3)
check_covariance_matrix(M)
#> [1] "Must have positive eigenvalues only"
test_covariance_matrix(M)
#> [1] FALSE
assert_covariance_matrix(M)
#> Error in eval(expr, envir, enclos): Assertion on 'M' failed: Must have positive eigenvalues only.
Check transistion probability matrix
And what about transition probability matrices?
### T1 is a transition probability matrix
T1 <- matrix(c(0.8, 0.2, 0, 0.1, 0.7, 0.4, 0.1, 0.1, 0.6), nrow = 3)
check_transition_probability_matrix(T1)
#> [1] TRUE
test_transition_probability_matrix(T1)
#> [1] TRUE
assert_transition_probability_matrix(T1)
### T2 is not a transition probability matrix
T2 <- matrix(c(0.8, 0.2, 0.1, 0.1, 0.7, 0.4, 0.1, 0.1, 0.6), nrow = 3)
check_transition_probability_matrix(T2)
#> [1] "Must have row sums equal to 1"
test_transition_probability_matrix(T2)
#> [1] FALSE
assert_transition_probability_matrix(T2)
#> Error in eval(expr, envir, enclos): Assertion on 'T2' failed: Must have row sums equal to 1.
Cholesky root of covariance matrix
(cov <- sample_covariance_matrix(4))
#> [,1] [,2] [,3] [,4]
#> [1,] 0.5506687 -0.6360957 -1.131468 1.461452
#> [2,] -0.6360957 1.2287961 1.632546 -2.289933
#> [3,] -1.1314677 1.6325459 3.531512 -2.753927
#> [4,] 1.4614522 -2.2899326 -2.753927 5.319355
(chol <- cov_to_chol(cov))
#> [1] 0.7420705 -0.8571904 -1.5247442 1.9694248 0.7028661 0.4631747
#> [7] -0.8561524 0.9960605 0.6480433 0.5364358
all.equal(cov, chol_to_cov(chol))
#> [1] TRUE