【问题标题】:Simulating samples in R, storing them and calculating test statistic在 R 中模拟样本,存储它们并计算测试统计量
【发布时间】:2013-12-21 07:35:12
【问题描述】:

我使用蒙特卡罗算法通过反演采样生成几何分布大小为 100 的数据样本:

gi.cdf.geom <- function(p,u){
k <- c()
k <- ceiling(log(1-u)/log(1-p)) - 1
return(k)
}

上面的函数是几何分布的CDF的倒数

u1 <- runif(100)
gen.gi.cdf1 <- gi.cdf.geom(50/239,u1)
as.data.frame(table(gen.gi.cdf1))

我不知道该怎么做是随机模拟 1000 个大小为 100 的数据样本,并计算每个样本的卡方检验统计量。我创建示例的尝试如下:

for(i in 1:1000){
 n=100
 p=50/239
 {
  u=runif(n)
  values <- gi.cdf.geom(p,u)
 }
 print(values)

}

但是,这给了我控制台的所有示例,以后无法引用它们。

非常感谢您的帮助。

谢谢

【问题讨论】:

    标签: r montecarlo resampling chi-squared


    【解决方案1】:

    使用replicate。例如:

    (x <- replicate(3,rgeom(10,50/239)))
          [,1] [,2] [,3]
     [1,]    5    3   12
     [2,]   15    2    3
     [3,]    5    5    0
     [4,]    4    2    1
     [5,]   13    0    8
     [6,]    0    3    0
     [7,]    3    1    6
     [8,]    0    6    2
     [9,]    0    4    4
    [10,]    8    4    1
    

    您可以使用apply 对其进行测试

    apply(x,2,chisq.test)
    [[1]]
    
            Chi-squared test for given probabilities
    
    data:  newX[, i] 
    X-squared = 47.566, df = 9, p-value = 3.078e-07
    
    
    [[2]]
    
            Chi-squared test for given probabilities
    
    data:  newX[, i] 
    X-squared = 10, df = 9, p-value = 0.3505
    
    
    [[3]]
    
            Chi-squared test for given probabilities
    
    data:  newX[, i] 
    X-squared = 37.3243, df = 9, p-value = 2.303e-05
    
    
    Warning messages:
    1: In FUN(newX[, i], ...) : Chi-squared approximation may be incorrect
    2: In FUN(newX[, i], ...) : Chi-squared approximation may be incorrect
    

    【讨论】:

    • 但是我怎样才能在表达式参数中放入 2 个表达式呢?因为我需要它每次从均匀分布中随机抽取 100 个样本,并使用每个样本来计算函数 gi.cdf.geom
    • 您可以将runif 放入您的函数调用中:gi.cdf.geom(p,runif(n))。否则,多个表达式可以放在花括号中并用分号分隔
    猜你喜欢
    • 1970-01-01
    • 2015-03-18
    • 1970-01-01
    • 1970-01-01
    • 2011-02-10
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    相关资源
    最近更新 更多