计算每次复制的平均值 [英] Calculating the mean of every replication

查看:113
本文介绍了计算每次复制的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码

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

res <- replicate(nsim, {
    load <- runif(10,11,14)
    diff <- load - demand    ## DIFFERENCE BETWEEN DEMAND AND LOAD 
    return(sum(diff < 0))
})
res
[1] 6 5 7 4 4 5 4 3 6 4 5 5 5 4 2 5 3 3 3 5 3 2 4 6 5 4 4 3 5 6 4 4 3 6 5 3 5 5 4 3 3
[42] 6 4 4 4 6 6 5 4 5

我有一个庞大的数据集,问题是什么是计算每个复制平均值的最快方法.例如,第一次复制中的res为6,因此对于第二次6 + 5/2 = 5.5,对于第三次6 + 5 + 7/3 = 6,结果应为6/1 = 6,而对于最后一次复制,结果应为sum(res )/nsim=4.38

I have a huge data set and the question is what is the fastest way of calculating the mean for every replication. For example the res in first replication is 6 so the result should be 6/1=6 for the second 6+5/2=5.5 for the third 6+5+7/3=6 and for the last replication is sum(res)/nsim=4.38

推荐答案

在问题的编辑版本中(2月11日,5:53编辑),OP指定了预期结果.这些表明OP可能正在寻找结果向量res累计平均值:

In the edited version of the question (edit of Feb 11 at 5:53), the OP has specified the expected result. These indicate that the OP might be looking for a cumulative mean of the result vector res:

cumsum(res)/seq_along(res)
# [1] 6.000000 5.500000 6.000000 5.500000 5.200000 5.166667 5.000000 4.750000 4.888889
#[10] 4.800000 4.818182 4.833333 4.846154 4.785714 4.600000 4.625000 4.529412 4.444444
#[19] 4.368421 4.400000 4.333333 4.227273 4.217391 4.291667 4.320000 4.307692 4.296296
#[28] 4.250000 4.275862 4.333333 4.322581 4.312500 4.272727 4.323529 4.342857 4.305556
#[37] 4.324324 4.342105 4.333333 4.300000 4.268293 4.309524 4.302326 4.295455 4.288889
#[46] 4.326087 4.361702 4.375000 4.367347 4.380000

或者,可以使用dplyr::cummean(res).

这篇关于计算每次复制的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆