How do I find the rolling mean since the beginning of data using R?

。_饼干妹妹 提交于 2019-12-02 11:22:55

问题


I am trying to find the rolling mean since the beginning of the data:

samp <- structure(list(samp = c(0.25, 0.4868, 0.6043, 0.5184, -0.3572, 
0.4685, 0.8264, 0.8445, 0.1331, 0.293, 0.4756, 0.866, 0.6461, 
0.0401, 0.0054, 0.0744, 0.6973, 0.6304, 0.5488, 0.5468, -0.2565, 
0.2557, 0.0557, 0.3347, 0.7584, 0.3547, 0.2577, 0.1238, 0.2184, 
0.5956, 0.4695, 0.6517, 0.7003, 0.8364, 0.5869, 0.4403, 0.538, 
0.6168, 1.0843, 1.1801, 0.617, 0.8869, 0.8073, 0.7787, 0.5705, 
0.8436, 0.8202, 0.847, 0.8608, 0.8978, 0.7012, 0.8892, 0.8463, 
0.7133, 0.9483, 0.9787, 0.9875, 0.8613, 0.976, 0.8893, 0.7906, 
0.6472, 0.8928, 0.7855, 0.7596, 1.0218)), .Names = "samp", row.names = c(NA, 
-66L), class = "data.frame")

I thought this would work:

library(zoo)
mean <-data.frame(rollmean(samp, 1:nrow(samp)))

I am trying to avoid writing loops...


回答1:


How about cumsum(samp$samp)/1:nrow(samp)




回答2:


You could use cummean from dplyr.

cummean(samp$samp)


来源:https://stackoverflow.com/questions/29201993/how-do-i-find-the-rolling-mean-since-the-beginning-of-data-using-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!