Generate a data frame with a predetermined correlation structure
Source:R/FUNCTIONS_GENERATE_DATA.R
generate_correlation_matrix.RdSimulates multivariate normal data whose columns reproduce a target correlation matrix, using Cholesky decomposition. If no matrix is supplied, a random symmetric positive-definite matrix is generated automatically.
Value
A data frame with nrows rows and ncol(correlation_martix)
columns of simulated numeric values.
Details
Uses Cholesky decomposition (chol()) to factor the target correlation
matrix, then multiplies by independent standard normal draws to produce correlated
columns. The resulting correlations approximate the target matrix, with accuracy
improving as nrows increases.
Examples
df <- data.frame(matrix(.999, ncol = 2, nrow = 2))
correlation_martix <- as.matrix(df)
diag(correlation_martix) <- 1
df <- generate_correlation_matrix(correlation_martix, nrows = 100)
stats::cor(df)
#> X1 X2
#> X1 1.0000 0.9989
#> X2 0.9989 1.0000