Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R repetitive math equation over vector

Tags:

r

time-series

I have a vector looks like this:

> y
 [1] 6.7 5.3 3.3 6.7 3.3 4.7 4.7 6.7 3.3 6.7

And I was trying to calculate the estimated auto-covariance when the time shift h = 3 using the formula below:

enter image description here

This is what I have done and I am wondering is there an easy way to do it than hard coding:

> 1/10 * (
+     (y[4] - mean(y))*(y[1] - mean(y)) + 
+     (y[5] - mean(y))*(y[2] - mean(y)) + 
+     (y[6] - mean(y))*(y[3] - mean(y)) + 
+     (y[7] - mean(y))*(y[4] - mean(y)) + 
+     (y[8] - mean(y))*(y[5] - mean(y)) + 
+     (y[9] - mean(y))*(y[6] - mean(y)) + 
+     (y[10] - mean(y))*(y[7] - mean(y))
+ )
[1] -0.04848
like image 946
B.Mr.W. Avatar asked Jan 19 '26 05:01

B.Mr.W.


2 Answers

You can define your own function like this:

my.cov <- function(y,h){
  y.bar <- mean(y)
  T <- length(y)
  (1/T) * sum((y[(h+1):T] - y.bar) * (y[1:(T-h)] -y.bar))
}
#Checking the function
> y <- c(6.7, 5.3, 3.3, 6.7, 3.3, 4.7, 4.7, 6.7, 3.3, 6.7)
> my.cov(y, h=3)
[1] -0.04848

Note that no for loop is involved since * is a vectorized operator.

like image 98
Jilber Urbina Avatar answered Jan 20 '26 19:01

Jilber Urbina


I'd do this vectorized instead of using a loop. Faster and a bit cleaner:

> y <- c(6.7,5.3,3.3,6.7,3.3,4.7,4.7,6.7,3.3,6.7)
> t <- 1:7
> (1/10)*sum((y[t+3]-mean(y))*(y[t]-mean(y)))
[1] -0.04848

And it is trivial to turn this into a function...

foo <- function(x,lag) {
    n <- length(x)
    i <- 1:(n-lag)
    (1/n) * sum( (y[ i + lag ] - mean(y) ) *( y[ i ] - mean(y) ) )
    }

foo( y , 3 )
# [1] -0.04848
like image 36
David Avatar answered Jan 20 '26 20:01

David



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!