R generates fewer random numbers than specified in rnorm, rexp, rpois and runif

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) # 1st method
group2 = rnorm(n = (N - N*p)) # 2nd method    

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.

#### EXAMPLE SCRIPT #####

N = 1000
p1 = seq(0.01, 0.99, 0.001)
q1 = 1 - p1


### FIRST METHOD ###

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) # column three + coulmn four should sum to 1000


### SECOND METHOD ###

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) # column three + coulmn four should sum to 1000
+1
1

R FAQ 7.31 - - :

> p=0.32
> p*1000 + (1-p)*1000
[1]1000

, . ?

> (p*1000 + (1-p)*1000) == 1000
[1] FALSE

. ? ?

> (p*1000 + (1-p)*1000) - 1000
[1] -1.136868e-13

1 10 ^ -13. :

> length(runif(1000*p))
[1] 320
> length(runif(1000*(1-p)))
[1] 679

:

> as.integer(1000*p)
[1] 320
> as.integer(1000*(1-p))
[1] 679

999. . R FAQ 7.31

, .

> Np = as.integer(1000*p)
> length(runif(Np))
[1] 320
> length(runif(1000-Np))
[1] 680

q 1-p N, 1000-N*p.

+5

All Articles