【问题标题】:R, how could I get same results using function "for" to get the result from "replicate"?R,我如何使用函数“for”从“replicate”中获得相同的结果?
【发布时间】:2016-11-23 08:14:34
【问题描述】:

我希望使用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)
}) 

通过使用for 函数。我试过的代码是这样的。

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)
}

但上面的代码不能正常工作。

【问题讨论】:

  • 我很难理解为什么当矢量化(因此通常更好)的方式工作得很好时,你为什么要使用for...?
  • z&lt;-vector("numeric", n) 排除在外。在当前情况下,在每次迭代中,z 都会被初始化(再次)

标签: r for-loop replicate


【解决方案1】:
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

【讨论】:

  • 检查这个太晚了。非常感谢!!
猜你喜欢
  • 2019-03-06
  • 2021-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-12
  • 2019-04-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多