After trying several variations of coding from the function I’m trying to make, still I’m not success. Here’s the equation below that I wish to make a function of it in R,

Edit: s here is of course less than T.
Also, here’s the two matrix that shows where the wij, zj(t), and zi(t+s) be taken from.

Hence, wij = w12 is equal to w1,2 in wmatrix. Similarly, zj(t) = z2(1) is equal to a2,1 in datamat. Again, i=j. Thus if i=1, t=1 and s = 1, then we have zi(t+s) = z1(1+1) = z1(2) which is equal to a1,2 in datamat matrix.
Now, Here’s the code that I ended up with,
st.acf <- function(datamat, wmatrix,ss){
a = dim(datamat)[1]
b = dim(datamat)[2]
sumn <- 0
for(i in 1:a){
for(j in 1:a){
for(t in 1:b-ss){
sumn <- sumn + wmatrix[i,j]*datamat[j,t]*datamat[i,t+ss]
}
}
}
print(sumn/sqrt(sum((wmatrix%*%datamat)^2)*sum(datamat^2)))
}
I used an example which I computed manually, and here’s the data of it,
DataMatrix <- rbind(c(54, 55, 51), c(52, 51, 57))
WeightsMatrix <- rbind(c(0, 1), c(1, 0))
The answer of this should be 0.66389. But, when I use my function, the output of it says numeric(0).
st.acf(DataMatrix, WeightsMatrix, 1)
numeric(0)
I can’t understand this, all the codes in my function is correct, when I run the loop, and the
sqrt(sum((wmatrix%*%datamat)^2)*sum(datamat^2)) separately, I got the correct answer. But, when I try to merge them and make a function, I always got numeric(0). Anyone can help me on this.
I’ll appreciate it very much!
In R, the
:operator has higher precedence than the binary-. Which means that1:b-ssis equivalent to(1:b)-ss, when you meant to use1:(b-ss). Make that change in your code and you will get the expected result.For more details on operator precedence, see
?Syntax.