首页 > 解决方案 > 在 R 中使用 runif 的不同结果

问题描述

我遇到了 for 循环和 runif() 函数的问题。我的目标是从两个均匀分布 U(0,2) 中确定回归线。问题是我正在使用 for 循环来模拟 runif 中的几个数量,然后计算回归线。例如,从 100:1000 开始的 10 次模拟,每次增量为 100。所以这给了我一些价值观

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

但是,如果我取出 for 循环并“手动”设置观察次数,则 a 和 b 的结果与循环的结果不同。我=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

这与之前的结果明显不同

也许这与 set.seed 有关,但我不知道。谢谢你,任何帮助将不胜感激

标签: rfor-looprandom-seeduniform-distribution

解决方案


我相信这是一个范围界定问题......所以如果你把设置的种子放在循环中。函数就像全局环境中的一个环境,所以我相信如果你把种子放在函数中,它应该可以修复它。

所以在这里:

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)

推荐阅读