0

I would like to have a same result of this code using replicate function,

set.seed(1)
n <- 100
sides <- 6
p <- 1/sides
zs <- replicate(10000,{
x <- sample(1:sides,n,replace=TRUE)
(mean(x==6) - p) / sqrt(p*(1-p)/n)
}) 

by using for function. Code I've tried is like this.

n<-10000
side<-6
p<-1/side
set.seed(1)
for(i in 1:n){
z<-vector("numeric", n)
x<-sample(1:side, 100, replace=TRUE)
z[i]<-mean(x==6)
}

But code above doesn't work well.

Cath
  • 23,906
  • 5
  • 52
  • 86
  • I'm struggling to see why you would want to use `for` when a vectorized (and therefore usually better) way works perfectly fine...? – LAP Nov 23 '16 at 08:26
  • 1
    Take `z<-vector("numeric", n)` out of the loop. In the current case, at every iteration, z is initialized (again) – etienne Nov 23 '16 at 08:27

1 Answers1

0
Try this:

set.seed(1)
n <- 100
sides <- 6
p <- 1/sides
zs <- replicate(10000,{
  x <- sample(1:sides,n,replace=TRUE)
  (mean(x==6) - p) / sqrt(p*(1-p)/n)
})

n<-10000
sides<-6
p<-1/sides
set.seed(1)
z<-vector("numeric", n)
for(i in 1:n){
  x<-sample(1:sides, 100, replace=TRUE)
  z[i]<-(mean(x==6) - p) / sqrt(p*(1-p)/100)
}

all(zs == z)
# TRUE
Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63