jeudi 1 juin 2017

How to generate random numbers of multivariate normal distribution with limits in R?

I want to generate random numbers of multivariate normal distribution with lower and upper limits. Following is a sample code:

x1 <- qnorm(runif(100,min=pnorm(0),max=pnorm(1)))*(100-10)+10
x2 <- qnorm(runif(100,min=pnorm(0),max=pnorm(1)))
x3 <- qnorm(runif(100,min=pnorm(0),max=pnorm(1)))*(10-0.01)+0.01

x <- as.matrix(cbind(x1,x2,x3))

mu <- colMeans(x)
sigma <- cov(x)

library(mvtnorm)
x.test <- rmvnorm(n=10000, mean=mu, sigma=sigma)

mu.test <- colMeans(x.test)
sigma.test <- cov(x.test)

all.equal(mu,mu.test)
all.equal(sigma,sigma.test)

x.test.sub <- subset(x.test, 
             x.test[,1] <= 100 & x.test[,1] >= 10 & 
               x.test[,2] <= 1 & x.test[,2] >= 0 & 
               x.test[,3] <= 10 & x.test[,3] >= 0.01)

print(nrow(x.test.sub))

You can see some rows outside the limits. So could somebody please tell me how I modify the code to perform a random sample of multivariate normal distribution with limits? Thanks in advance!




Aucun commentaire:

Enregistrer un commentaire