rfor-looprandom-seeduniform-distribution

Different results using runif in R


I'm having an issue with a for loop and the runif() function. My goal is to determine a regression line out of two Uniform Distributions U(0,2). The thing is I'm using a for loop to simulate several quantities out of the runif and then calculate the regression line. For instance, 10 simulations from 100:1000 with an increment of 100 each time. So that gives me some values

set.seed(69420)

#Vr<-matrix(data= ,nrow =10, ncol=2)

i<-0
for(j in 1:10){
for(i in x){
i<-i+100
J<-runif(i , min=0 , max=2)
M<-runif(i , min=0 , max=2)

L<-pmax(J,M)#assign time to loser 
W<-pmin(J,M)#assign time to winner

mW<-mean(W)
mL<-mean(L)

plot(W,L,xlim=c(0,2),ylim=c(0,2))
abline(v=0,col='salmon')
abline(h=0,col='steelblue')

vW<-mean((W-mean(W))^2) 
vL<-mean((L-mean(L))^2) 

cWL<-mean((L-mean(L))*(W-mean(W)))

a=cWL/vW
b=mean(L) - (cWL*mean(W))/vW
#Vr[j,1]<-c(a)
#Vr[j,2]<-c(b)

abline(b,a,lwd=2, col="gray60")

}

[1,] 0.3649283 1.1337290
 [2,] 0.4455959 1.0407265
 [3,] 0.5418103 0.9433790
 [4,] 0.4919243 1.0179350
 [5,] 0.5271277 0.9813729
 [6,] 0.5328144 0.9743172
 [7,] 0.5095540 0.9860148
 [8,] 0.5022895 0.9942346
 [9,] 0.5663103 0.9276580
[10,] 0.5258270 0.9848213

But if then I take out the for loop and set the numbers of observations 'manually', the outcome for a and b is different from the one with the loop. i=1000

set.seed(69420)

#Vr<-matrix(data= ,nrow =10, ncol=2)

i<-0

J<-runif(1000 , min=0 , max=2)
M<-runif(1000 , min=0 , max=2)

L<-pmax(J,M)#assign time to loser 
W<-pmin(J,M)#assign time to winner

mW<-mean(W)
mL<-mean(L)

plot(W,L,xlim=c(0,2),ylim=c(0,2))
abline(v=0,col='salmon')
abline(h=0,col='steelblue')

vW<-mean((W-mean(W))^2) 
vL<-mean((L-mean(L))^2) 

cWL<-mean((L-mean(L))*(W-mean(W)))

a=cWL/vW
b=mean(L) - (cWL*mean(W))/vW

abline(b,a,lwd=2, col="gray60")

and the result is
[1] 0.4766998 1.010351

which clearly differs from the previous result

Maybe it´s something to do with the set.seed but i dont know. Thank you and any help would be greatly appreciated


Solution

  • I believe this is a scoping issue.... so if you put the set seed within the the loop. Functions are like an environment within the global environment, so I believe if you put the seed within the function it should fix it.

    so here:

    i<-0
    for(j in 1:10){
    for(i in x){
    set.seed(69420)
    i<-i+100
    J<-runif(i , min=0 , max=2)
    M<-runif(i , min=0 , max=2)