Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving Average using R code

Tags:

r

The first part I need to have R code is about:

Write an R function that does the following: Given a sequence xN = (x1; x2; ...; xN) of N observations, the function returns a vector of moving averages, where each average is computed with k consecutive observations. Name the function ma, and its arguments are the vector xN and k.

What I have so far:

x <-vector(length=n)

ma <- function(x,k){
x0 <- x[1:(length(x)-k)]
x1 <- x[(1+k):length(x)]
cor(x0, x1)
}

I'm pretty sure that I made mistakes...

like image 365
Keris Avatar asked Apr 18 '26 22:04

Keris


1 Answers

There are loads of ways of calculating moving averages.

in base r, this can work

filter(x, rep(1/2,2)) #this calculates moving average of 2 numbers in a sequence
filter(x, rep(1/3,3))  #this calculates moving average of 3 numbers in a sequence

for k consecutive observations

filter(x, rep(1/k,k))

e.g.

x <- c(3,5,7,3,4,2,6,4,7,2,1,9, 1, 10, 1,12)
filter(x, rep(1/2,2))
# [1] 4.0 6.0 5.0 3.5 3.0 4.0 5.0 5.5 4.5 1.5 5.0 5.0 5.5 5.5 6.5  NA

You should also look up the following packages: zoo and TTR packages for more options

Just as a quick example, the function runMean in TTR is super easy

runMean(x,2) #gives rolling mean of every 2 consecutive observations
runMean(x,k) #gives rolling mean of every k consecutive observations
like image 151
jalapic Avatar answered Apr 20 '26 13:04

jalapic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!