I have a covariance function type of two lags: h1 and h2. I am trying to avoid for loops to create the covariance function matrix. When I type cov1 it does not give me a matrix. Just a vector if I type for example covmatrix(h1=1:5,h2=1:5). How can I obtain for example the whole 5 by 5 matrix.

I tried all apply functions, and the new vectorize function (with lower case v)

R code:

x=arima.sim(n = 100   , list(ar = .5))
cov=function(h1,h2){
     (1/n)*sum((x[1:(n-h1-h2)]-mean(x))*(x[(1+h1):(n-h2)]-mean(x))*(x[(1+h1+h2):n]-mean(x)))
}
covmatrix=Vectorize(cov)

1 Answers

1
erocoar On

A simple double-apply should get you what you are looking for. Note how the return value of the vectorized function is equal to the diagonal of the covmatrix.

test <- sapply(1:5, function(x) sapply(1:5, function(y) cov(x, y)))
all.equal(diag(test), covmatrix(1:5, 1:5))