繁体   English   中英

(简单)在R中生成多个(1000)随机变量

[英](Simple) Generating Multiple (1000) random variables in R

我正在尝试创建1000个特定变量Z的样本,其中首先生成12个均匀RV的U i ,然后从i = 1到12具有Z = ∑(U i -6)。

u <- runif(12)
Z <- sum(u-6)

但是我不确定如何重复那1000倍。 最后,我们希望绘制出Z的直方图,理想情况下,它要类似于法线曲线。 抱歉,很明显,我是这个领域的初学者。 谢谢!

如果我理解这个问题,这是一种非常简单的方法-使用replicate()可以根据需要多次执行计算。

# number of values to draw per iteration 
n_samples <- 12

# number of iterations 
n_iters <- 1000

# get samples, subtract 6 from each element, sum them (1000x)
Zs <- replicate(n_iters, sum(runif(n_samples) - 6))

# print a histogram 
hist(Zs)

这是你所追求的吗?

set.seed(2017);
n <- 1000;
u <- matrix(runif(12 * n), ncol = 12);
z <- apply(u, 1, function(x) sum(x - 6));

# Density plot
require(ggplot2);
ggplot(data.frame(z = z), aes(x = z)) + geom_density();

在此处输入图片说明

说明:一次性绘制12 * 1000均匀样本,存储在1000 x 12矩阵中,然后对行条目x - 6求和。

暂无
暂无

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

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