mvrandn: Truncated multivariate normal generator

Description Usage Arguments Details Value Note See Also Examples

View source: R/mvrandn.R

Description

Simulate n independent and identically distributed random vectors from the d-dimensional N(0,Σ) distribution (zero-mean normal with covariance Σ) conditional on l<X<u. Infinite values for l and u are accepted.

Usage

1
mvrandn(l, u, Sig, n, mu = NULL)

Arguments

l

lower truncation limit

u

upper truncation limit

Sig

covariance matrix

n

number of simulated vectors

mu

location parameter

Details

Value

a d by n matrix storing the random vectors, X, drawn from N(0,Σ), conditional on l<X<u;

Note

The algorithm may not work or be very inefficient if Σ is close to being rank deficient.

See Also

mvNqmc, mvNcdf

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
 # Bivariate example.

 Sig <- matrix(c(1,0.9,0.9,1), 2, 2);
 mu <- c(-3,0); l <- c(-Inf,-Inf); u <- c(-6,Inf);
 A <- matrix(c(1,0,-1,1),2,2);
 n <- 1e3; # number of sampled vectors
 Y <- mvrandn(l - A %*% mu, u - A %*% mu, A %*% Sig %*% t(A), n);
 X <- rep(mu, n) + solve(A, diag(2)) %*% Y;
 # now apply the inverse map as explained above
 plot(X[1,], X[2,]) # provide a scatterplot of exactly simulated points
## Not run: 
# Exact Bayesian Posterior Simulation Example.

data("lupus"); # load lupus data
Y = lupus[,1]; # response data
X = lupus[,-1]  # construct design matrix
m=dim(X)[1]; d=dim(X)[2]; # dimensions of problem
 X=diag(2*Y-1) %*%X; # incorporate response into design matrix
 nu=sqrt(10000); # prior scale parameter
 C=solve(diag(d)/nu^2+t(X)%*%X);
 L=t(chol(t(C))); # lower Cholesky decomposition
 Sig=diag(m)+nu^2*X %*% t(X); # this is covariance of Z given beta
 l=rep(0,m);u=rep(Inf,m);
 est=mvNcdf(l,u,Sig,1e3);
 # estimate acceptance probability of Crude Monte Carlo
 print(est$upbnd/est$prob)
 # estimate the reciprocal of acceptance probability
 n=1e4 # number of iid variables
 z=mvrandn(l,u,Sig,n);
 # sample exactly from auxiliary distribution
 beta=L %*% matrix(rnorm(d*n),d,n)+C %*% t(X) %*% z;
 # simulate beta given Z and plot boxplots of marginals
 boxplot(t(beta))
 # plot the boxplots of the marginal
 # distribution of the coefficients in beta
 print(rowMeans(beta)) # output the posterior means
 
## End(Not run)

Example output

[1] 5.379046
    const        x1        x2 
-3.013169  6.880176  3.968340 

TruncatedNormal documentation built on Sept. 8, 2021, 5:07 p.m.