The function dwishart() computes the density of a Wishart distribution.
The function rwishart() samples from a Wishart distribution.
The functions with suffix _cpp perform no input checks, hence are faster.
Usage
dwishart_cpp(x, df, scale, log = FALSE, inv = FALSE)
rwishart_cpp(df, scale, inv = FALSE)
dwishart(x, df, scale, log = FALSE, inv = FALSE)
rwishart(df, scale, inv = FALSE)See also
Other simulation helpers:
Simulator,
correlated_regressors(),
ddirichlet_cpp(),
dmixnorm_cpp(),
dmvnorm_cpp(),
dtnorm_cpp(),
gaussian_tv(),
simulate_markov_chain()
Examples
x <- diag(2)
df <- 6
scale <- matrix(c(1, -0.3, -0.3, 0.8), ncol = 2)
# compute density
dwishart(x = x, df = df, scale = scale)
#> [1] 0.002607893
dwishart(x = x, df = df, scale = scale, log = TRUE)
#> [1] -5.949213
dwishart(x = x, df = df, scale = scale, inv = TRUE)
#> [1] 0.0004824907
# sample
rwishart(df = df, scale = scale)
#> [,1] [,2]
#> [1,] 5.132976 -3.211344
#> [2,] -3.211344 5.962176
rwishart(df = df, scale = scale, inv = TRUE)
#> [,1] [,2]
#> [1,] 0.12122863 -0.04057652
#> [2,] -0.04057652 0.13116231
# expectation of Wishart is df * scale
n <- 100
replicate(n, rwishart(df = df, scale = scale), simplify = FALSE) |>
Reduce(f = "+") / n
#> [,1] [,2]
#> [1,] 6.177993 -1.907376
#> [2,] -1.907376 4.736363
df * scale
#> [,1] [,2]
#> [1,] 6.0 -1.8
#> [2,] -1.8 4.8
# expectation of inverse Wishart is scale / (df - p - 1)
n <- 100
replicate(n, rwishart(df = df, scale = scale, TRUE), simplify = FALSE) |>
Reduce(f = "+") / n
#> [,1] [,2]
#> [1,] 0.34021873 -0.06558745
#> [2,] -0.06558745 0.31883506
scale / (df - 2 - 1)
#> [,1] [,2]
#> [1,] 0.3333333 -0.1000000
#> [2,] -0.1000000 0.2666667
