简体   繁体   English

R,我如何使用函数“ for”从“复制”中获得结果?

[英]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, 我希望使用replicate功能获得与此代码相同的结果,

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. 通过使用for函数。 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

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

相关问题 如何在R中复制一个function得到最后的结果? - How to replicate a function in R and get the last result? 我如何在R中不使用for循环的情况下获得相同的结果 - How do i get the same result without using a for loop in R 如何使用 dplyr 获得相同的分组结果以获得与 sqldf 结果一致的结果? - How to get same grouping results using dplyr to get result consistent with sqldf result? 如何在 R 中使用循环和并行获得相同的结果? - How to get same results using loop and parallel in R? 使用 tidyr " pivot " ZC1C4DFAB507C17A9 复制 R 中 " dcast " function 的结果。 重塑 dataframe - Replicate the results from " dcast " function in R using tidyr " pivot " function. Reshape dataframe 在 r 中,如何在没有 for 循环的情况下获得相同的结果? - how to get same result without for loop in r? 如何使用R从符号回归中获得函数结果 - How to get the function result from Symbolic Regression with R 我在 R 中总结 function 得到一个奇怪的结果 - I get a weird result in summarise function in R 如何设置种子以在 R 中使用复制功能存档模拟结果的再现性 - How Do I Set Seed to Archive Reproducibility of Simulation Result with Replicate Function in R 如何将封装函数的结果获取到R中的数据框中 - How to get result of package function into a dataframe in r
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM