使用平均值计数器在R中进行模拟

时间:2015-01-27 18:44:41

标签: r simulation

我有以下代码来计算正态分布随机数(mu = 245,sd = 24.5,n = 9)低于200的次数。

 # This is a simulation  to count the Binomial from B samples of
 # size n from a Normal population with mu and sigma that fall below 
 # a cutoff x_0   B = 100000; mu = 245; sigma = 24.5; n = 9  x_0 = 200 
 # for one sample  
 y_count = numeric(n) 
 y_average = numeric(n)
 x = numeric(n)  
for (i in 1:n){         
x[i] = rnorm(1,mu,sigma)         
    if (x[i] < x_0) y_count[i] = y_count[i] + 1 
}  
y_count  
sum(y_count) 

 # for B samples and computing the estimated probability 
 y_count = matrix(0,B,n) 
 x = matrix(0,B,n) 
 for (j in 1:B){         
      for (i in 1:n){                 
       x[j,i] = rnorm(1,mu,sigma)                
       if (x[j,i] < x_0) y_count[j,i] = y_count[j,i] + 1         
    } }  
 y_count  
 y_count_rows = apply(y_count,1,sum) 
 y_count_rows  
 prob_est = sum(y_count_rows)/B
 prob_est  

我希望能够计算9次重复的平均值低于200的频率,我怎样才能在R中修改此程序

1 个答案:

答案 0 :(得分:3)

这对你有用吗?它使用pnorm()函数,它是正态分布的累积密度函数(cdf)。对于给定的一组均值和西格玛值,它返回给定值x_0以下的区域。

mu=245
sigma = 24.5
x_0 = 200
pnorm(q=x_0, mean=mu, sd=sigma)

[1] 0.03312454

即,它指出,随机分布中有大约3.31%的抽取量与mu和sigma将低于该阈值。