I have to generate random numbers for two groups of a vector of size N.
The probability for one group is p, and for the other, q = 1-p. (For example, for a population of 1000 with p = 0.5, I have to generate 500 random numbers from the distribution and 500 from another). Since this is a simulation in which I have to change the "p", I wrote my code to create the following:
group1 = rnorm(n = N*p)
group2 = rnorm(n = N*q)
group2 = rnorm(n = (N - N*p))
When using both of the above methods, R generates one less number of random numbers than it should be in several lines of group2 (about 35% of lines with the first and about 12% of lines with the second method).
I ran into the same error with rexp, rpois and runif.
Below is a snapshot of both methods for your reference.
N = 1000
p1 = seq(0.01, 0.99, 0.001)
q1 = 1 - p1
X = data.frame()
for (i in 1:length(p1))
{
X[i, 1] = p1[i]
X[i, 2] = q1[i]
X[i, 3] = length(runif((N * X[i, 1])))
X[i, 4] = length(runif((N * X[i, 2])))
X[i, 5] = X[i, 4] + X[i, 3]
}
table(X[, 5] == 1000)
Y = data.frame()
for (i in 1:length(p1))
{
Y[i, 1] = p1[i]
Y[i, 2] = q1[i]
Y[i, 3] = length(runif((N * Y[i, 1])))
Y[i, 4] = length(runif((N - N * Y[i, 1])))
Y[i, 5] = Y[i, 3] + Y[i, 4]
}
table(Y[, 5] == 1000)