在R模拟中设置计数器

时间:2015-01-23 19:09:08

标签: r simulation

我想在R中进行模拟。我想使用大量的试验建立一个循环。具体来说,我想使用具有已知均值,标准偏差和N = 9的正态分布。我想设置一个计数器,该计数器计算重复次数低于(或高于)某个值的次数。另外,我想看到生成数据的直方图。

2 个答案:

答案 0 :(得分:0)

不是循环的忠实粉丝,所以我会做这样的事情:

func<-function(n){
  counter=0
  x<-rnorm(1,0,1)
  if(x>2|x<(-2)) counter<-1
  return(c(n,x,counter))
}
n=1:1000
sum(do.call(rbind,lapply(n,func))[,3])



> sum(do.call(rbind,lapply(n,func))[,3])
[1] 41
> sum(do.call(rbind,lapply(n,func))[,3])
[1] 43
> sum(do.call(rbind,lapply(n,func))[,3])
[1] 43
> sum(do.call(rbind,lapply(n,func))[,3])
[1] 39

do.call(rbind,lapply(n,func))将为您提供制作数字直方图所需的实际数据:

dat<-data.frame(do.call(rbind,lapply(n,func)))
names(dat)<-c("n","x","counter")
head(dat)
  n          x counter
1 1 -0.6591145       0
2 2  1.8163984       0
3 3 -2.0291848       1
4 4  0.3309398       0
5 5 -0.8214298       0
6 6  0.5275238       0  

答案 1 :(得分:0)

沿着这些方向尝试一些事情。

#in this structure each row in the matrix is a sim rep
sim.data<- matrix(rnorm(9*1000,0,1),1000,9)

#this counts number of observations below threshold for each rep
below <- apply(sim.data, 1, function(x) sum(x<0.60))

hist(below)
相关问题