简体   繁体   中英

R, how could I get same results using function “for” to get the result from “replicate”?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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