0

I'm attempting to create 1000 samples of a certain variable Z, in which first I generate 12 uniform RV's Ui, and then have Z = ∑ (Ui-6) from i=1 to 12. I can generate one Z from

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

However I am not sure how to go about repeating that 1000x. In the end, the desire is to plot out the histogram of the Z's, and ideally it to resemble the normal curve. Sorry, clearly I am as beginner as you can get in this realm. Thank you!

sbv540
  • 23
  • 4

2 Answers2

1

If I understand the question, this is a pretty straightforward way to do it -- use replicate() to perform the calculation as many times as you want.

# 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)
lefft
  • 2,065
  • 13
  • 20
0

Is this what you're after?

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();

enter image description here

Explanation: Draw 12 * 1000 uniform samples in one go, store in a 1000 x 12 matrix, and then sum row entries x - 6.

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
  • Yes, exactly! Thanks a lot. One quick question, where did the "2017" value for set.seed stem from? – sbv540 Nov 21 '17 at 00:09
  • @sbv540 No worries. Glad to help. `set.seed` ensures reproducibility of random samples in the example by initialising the RNG with an arbitrary but fixed seed (in my case "2017"). See also `?set.seed`. It's usually [good practice](https://stackoverflow.com/questions/13605271/reasons-for-using-the-set-seed-function) when giving random sample data here on SO. – Maurits Evers Nov 21 '17 at 00:13