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))

1 Answers

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))