1

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 Answer 1

3

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)) 
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much Erocoar for your quick ans smart answer. It really works fine.
However this double sapply seems to be quite slow. Same amount as for loops. I wonder if there is a way to get Vectorize working properly

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.