首页 文章

在R模拟中设置计数器

提问于
浏览
0

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

2 回答

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

相关问题