繁体   English   中英

在R代码中生成100个均匀的不同随机变量

[英]Generating 100 uniform different random variables in R code

我正在尝试生成100个Z样本,其中Z是区间[0; 1]中8个独立均匀分布的随机变量的总和

到目前为止,我有以下代码,但是不确定是否正确。 我不确定我的循环是否正确

eight<-runif(8,0,1) #Uses the runif function to generate 8 uniform 0-1 random variables
   Z_1<-sum(eight)  #caclulates the sum and stores it in the variable Z_1
   sample <-NA


   for (i in 1:100 ) {  #Function continues the loop for 100 different values 
      eight<-runif(8,0,1); #Creates sum loop for 8 independent values uniform 0-1 random variables.
      Z_1<-sum(eight); # stores in the sum loop in the variable Z
      sample[i] = Z_1;
    }`

谢谢

我将整个事情矢量化。 当您一次运行只能生成800个观测值时,没有真正的理由运行100次迭代。 然后只需使用matrixcolSums可以了

set.seed(123)
n <- 100
Z <- colSums(matrix(runif(8 * n), 8, n))
Z
#  [1] 4.774425 4.671171 4.787691 4.804041 3.513257 2.330163 3.300135 3.568657 5.503481 2.861764 4.533283 3.353658
# [13] 4.230073 4.690739 4.364708 3.094156 4.933616 3.942834 3.712522 2.587036 3.731474 4.388749 4.484030 4.315968
# [25] 4.800758 4.252631 2.716972 5.159044 4.146881 3.244546 4.418618 4.350035 5.344182 3.176801 3.903337 2.261935
# [37] 3.646572 4.286075 3.074900 4.210506 3.172513 4.535665 4.245856 4.184848 4.532286 2.899883 4.473629 4.751224
# [49] 3.498038 3.337437 4.238989 3.349812 3.888696 4.748254 3.029479 4.246619 3.330434 3.879168 3.786216 3.839956
# [61] 3.878997 4.546531 2.863010 3.417072 4.266108 3.141875 4.960758 3.989613 4.373042 4.295742 4.459014 5.561066
# [73] 4.401990 4.121301 3.830575 3.412446 3.812347 5.591238 3.801587 4.454336 4.213343 5.222007 4.300991 2.765003
# [85] 3.293251 5.362586 2.954080 3.036312 3.655677 3.373603 5.575184 4.167740 3.904038 3.884440 2.901452 3.079311
# [97] 4.927770 3.930943 4.169907 2.922618

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM