transform correlation parameters to and from glmmTMB parameterization
vector of internal correlation parameters (elements of scaled Cholesky factor, in row-major order)
return a vector of correlation values from the lower triangle ("vec"), or the full correlation matrix ("mat")?
a correlation matrix
input a vector of correlation values from the lower triangle ("vec"), or the full correlation matrix ("mat")?
a vector of correlation values (get_cor) or glmmTMB scaled-correlation parameters (put_cor)
get_cor transforms from the glmmTMB parameterization (components of a theta parameter vector) to correlations;
put_cor does the inverse transformations, from correlations to theta values.
These functions follow the definition at http://kaskr.github.io/adcomp/classdensity_1_1UNSTRUCTURED__CORR__t.html:
if \(L\) is the lower-triangular matrix with 1 on the diagonal and the correlation parameters in the lower triangle, then the correlation matrix is defined as \(\Sigma = D^{-1/2} L L^\top D^{-1/2}\), where \(D = \textrm{diag}(L L^\top)\). For a single correlation parameter \(\theta_0\) (i.e. the correlation in a 2x2 correlation matrix), this works out to \(\rho = \theta_0/\sqrt{1+\theta_0^2}\). The get_cor function returns the elements of the lower triangle of the correlation matrix, in column-major order.
These functions also work for AR1 correlation parameters.
th0 <- 0.5
stopifnot(all.equal(get_cor(th0), th0/sqrt(1+th0^2)))
set.seed(101)
## pick 6 values for a random 4x4 correlation matrix
print(C <- get_cor(rnorm(6), return_val = "mat"), digits = 3)
#> [,1] [,2] [,3] [,4]
#> [1,] 1.000 -0.310 0.416 0.135
#> [2,] -0.310 1.000 -0.613 0.144
#> [3,] 0.416 -0.613 1.000 0.514
#> [4,] 0.135 0.144 0.514 1.000
## transform a correlation matrix to a theta vector
cor_mat <- matrix(c(1,0.3,0.1,
0.3,1,0.2,
0.1,0.2,1), ncol = 3)
put_cor(cor_mat, "mat")
#> [1] 0.3144855 0.1021557 0.1820500
put_cor(cor_mat[lower.tri(cor_mat)], "vec")
#> [1] 0.3144855 0.1021557 0.1820500
## test: round-trip
stopifnot(all.equal(get_cor(put_cor(C), return_val = "mat"), C))