Skip to contents

Modifies a correlation matrix by setting specific off-diagonal elements to desired values, then adjusts the matrix to ensure it remains positive definite. This is useful for creating correlation matrices with specific patterns while maintaining mathematical validity.

Usage

transform_rho(rho, el)

Arguments

rho

A correlation matrix

el

A matrix with 3 columns specifying the transformations to apply:

Column 1

Row indices (i) of correlations to modify

Column 2

Column indices (j) of correlations to modify

Column 3

New correlation values to set for rho[i,j]

All correlation values must be between -1 and 1

Value

A transformed correlation matrix that is positive definite. The function automatically ensures symmetry (sets both rho[i,j] and rho[j,i]) and uses nearPD to find the nearest positive definite matrix if the specified correlations make the matrix non-positive definite

Details

The function first sets the specified correlations in both symmetric positions of the matrix, then uses the nearPD function from the Matrix package to find the nearest positive definite correlation matrix. Information about the convergence is printed to the console.

See also

Examples

# Start with a random correlation matrix
rho <- rlkjcorr(n = 1, K = 4, eta = 1)
round(rho, 2)
#>       [,1]  [,2]  [,3]  [,4]
#> [1,]  1.00 -0.29 -0.61 -0.59
#> [2,] -0.29  1.00 -0.31 -0.15
#> [3,] -0.61 -0.31  1.00  0.91
#> [4,] -0.59 -0.15  0.91  1.00

# Define specific correlations to set
el <- rbind(
  c(i = 1, j = 2, r = +0.7), # Set correlation between variables 1 and 2 to 0.7
  c(i = 3, j = 4, r = -0.5)  # Set correlation between variables 3 and 4 to -0.5
)

# Transform the matrix
rho_new <- transform_rho(rho, el)
#> iterations: 14
#> converged: TRUE
round(rho_new, 2)
#>       [,1]  [,2]  [,3]  [,4]
#> [1,]  1.00  0.67 -0.53 -0.50
#> [2,]  0.67  1.00 -0.34 -0.17
#> [3,] -0.53 -0.34  1.00 -0.43
#> [4,] -0.50 -0.17 -0.43  1.00

# Verify the specified correlations were set
rho_new[1, 2]  # Should be close to 0.7
#> [1] 0.6709284
rho_new[3, 4]  # Should be close to -0.5
#> [1] -0.4335107