Solved – r – pick 10 random numbers from standard normal distribution whose sum equals 5

normal distributionr

I am having coding the following in R
I want to pick 10 random numbers from a standard normal distribution whose sum equals 5.
I have the following code so far (below), but this returns "numeric(0)" when the random numbers don't satisfy the condition. What I want is to choose 10 random numbers that do satisfy this condition. Is there a way to re-scale these numbers once they have been picked, or can I somehow insert a condition for this into "rnorm" ? Help very much appreciated!

a <- rnorm(10, 0, 1)

ones <- matrix(1, nrow=10, ncol=1 )

A <- a[t(a) %*% ones == 5]

Best Answer

The way I interpret this question, we are asking to generate from the distribution $(X_1, \ldots, X_{10} \mid \sum_{i = 1} ^ {10} X_i = 5)$ where $X_1, \ldots, X_n \stackrel {iid} \sim \mathcal N(0,1)$. This is easy enough - the joint distribution of $(X_1, \ldots, X_9, \sum_i X_i)$ is multivariate normal with mean vector $\mu = (0,\ldots,0)$ and covariance matrix

$$\Sigma = \pmatrix{1 & 0 & \ldots & 0 & 1 \\ 0 & 1 & \ldots & 0 & 1 \\ \vdots & \vdots & \cdots & \vdots & \vdots \\ 0 & 0 & \ldots & 1 & 1 \\ 1 & 1 & \ldots & 1 & 10}.$$

From this, it can be shown that $(X_1, \ldots, X_9 \mid \sum_i X_i)$ is, again, a normal distribution with mean $\mu^\star = (\bar X, \bar X, \ldots, \bar X)$ and covariance matrix $\Sigma^\star = \mathbf I - \frac 1 {10} \mathbf J$ where $\mathbf J$ is a matrix with all entries equal to $1$ - see, for example, here. So, to do this in R,

library(MASS)
Sigma  <- diag(9) - .1
X      <- numeric(10)
X[1:9] <- mvrnorm(1, rep(5 / 10, 9), Sigma)
X[10]  <- 5 - sum(X[1:9])

And now $(X_1, \ldots, X_{10})$ is drawn from the distribution $(X_1, \ldots, X_{10} \mid \sum_i X_i = 5)$.