I'm trying to use R to calculate the moving average over a series of values in a matrix. The normal R mailing list search hasn't been very helpful though. There doesn't seem to be a built-in function in R will allow me to calculate moving averages. Do any packages provide one? Or do I need to write my own?
相关问题
- R - Quantstart: Testing Strategy on Multiple Equit
- Using predict with svyglm
- Reshape matrix by rows
- Extract P-Values from Dunnett Test into a Table by
- split data frame into two by column value [duplica
相关文章
- How to convert summary output to a data frame?
- How to plot smoother curves in R
- Paste all possible diagonals of an n*n matrix or d
- ess-rdired: I get this error “no ESS process is as
- How to use doMC under Windows or alternative paral
- dyLimit for limited time in Dygraphs
- Saving state of Shiny app to be restored later
- How to insert pictures into each individual bar in
In fact
RcppRoll
is very good.The code posted by cantdutchthis must be corrected in the fourth line to the window be fixed:
Another way, which handles missings, is given here.
A third way, improving cantdutchthis code to calculate partial averages or not, follows:
The
caTools
package has very fast rolling mean/min/max/sd and few other functions. I've only worked withrunmean
andrunsd
and they are the fastest of any of the other packages mentioned to date.In order to complement the answer of cantdutchthis and Rodrigo Remedio;
You could use
RcppRoll
for very quick moving averages written in C++. Just call theroll_mean
function. Docs can be found here.Otherwise, this (slower) for loop should do the trick:
In data.table 1.12.0 new
frollmean
function has been added to compute fast and exact rolling mean carefully handlingNA
,NaN
and+Inf
,-Inf
values.As there is no reproducible example in the question there is not much more to address here.
You can find more info about
?frollmean
in manual, also available online at?frollmean
.Examples from manual below: