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

标签 r statistics

我正在尝试生成 Z 的 100 个样本,其中 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

关于r - 在R代码中生成100个均匀不同的随机变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27433458/

相关文章:

algorithm - 如何找到分布在多个服务器上的数字的平均值?

security - 这个密码生成器有偏见吗?

javascript - Google Analytics 和哈希/ anchor 不起作用

r - R 的 lavaan 中的模型识别

r - rgdal R 包中的 spTransform 中的 "Non Finite Transformation Detected"

sql-server - sql server 和统计配置文件

machine-learning - 为什么将神经网络质量表示为 1 减去预测的平均绝对误差与预测值范围的比率?

R plot() 生成俄语日期标签

r - 为什么 plotly() 和 enquo + !!在冲突?

r - 抑制R输出