Calculating the mean of every replication

前端 未结 2 1341
旧巷少年郎
旧巷少年郎 2021-01-29 15:26

I have the following code

set.seed(30)
nsim <- 50    ## NUMBER OF REPLICATIONS
demand <- c(12,13,24,12,13,12,14,10,11,10)

res <- replicate(nsim, {
             


        
2条回答
  •  耶瑟儿~
    2021-01-29 15:46

    To illustrate my comment, you can generate a matrix where columns (or rows, if you prefer) represent replications, after which you can use R's matrix operations capabilities:

    set.seed(47)    # make reproducible
    
    nsim <- 50    ## NUMBER OF REPLICATIONS
    demand <- c(12,13,24,12,13,12,14,10,11,10)
    
    loads <- matrix(runif(10 * nsim, 11, 14), ncol = nsim)
    
    diffs <- loads - demand    # with vector recycling
    # or: diffs <- apply(loads, 2, `-`, demand)    
    # or: diffs <- apply(loads, 2, function(x){x - demand})
    
    res <- colSums(diffs > 0)
    LOLE <- sum(res) / nsim
    
    LOLE
    #> [1] 5.7
    

提交回复
热议问题