I need to generate an n x n, positive-definite covariance matrix for a project. Drawing from the Wishart distribution was recommended. How do I generate a random covariance matrix in R, ideally also using the Wishart Distribution. I've tried rwishart() to get values, but need more help. Thanks
Please see the function documentation by running ?rWishart
.
As you can read, you need to supply the number of samples n
you want (i.e. n
random matrices), the degrees of freedom df
, and the parameter Sigma
to the function. In addition, you also need to decide on the dimension of the wanted random matrix.
# Set parameters
n <- 1 # Number of matrices
p <- 5 # Dimension
df <- 10 # Degrees of freedom
Sigma <- toeplitz((p:1)/p) # the matrix parameter of the distribution
# Draw n Wishart distributed matrices
rwish <- drop(rWishart(n, df, Sigma))
print(rwish)
The function generates a 1 x p x p array (effectively a matrix) but we drop the unneeded dimension.
You can generate a wishart distributed matrix "manually" by
library("mvtnorm")
rgaus <- rmvnorm(n = df, mean = rep(0, p), sigma = Sigma)
rwish2 <- crossprod(rgaus) # crossprod is the same as "t(rgaus) %*% rgaus"
which should help you understand better what the Wishart distribution actually is. It is the distribution of the so-called scatter matrix df
samples from a zero-mean multivariate normal distribution with variance Sigma
.