简体   繁体   中英

Vectorize function operating on a two-argument function

I have a two-argument function (auto-covariance function with two lags) to vectorize but I am not able to get the output of this as a matrix. I am trying to avoid for loops and all kinds of apply functions.

I was trying Vectorize and vectorize (new one). I wanted for example to have a 5 by 5 covariance matrix. When I type

covmatrix(h1 = 1:5, h2 = 1:5) 

I get only the diagonals and not the full matrix.

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)

I am expecting a matrix as the input is a two-argument function.

The way you are calling covmatrix is producing the right result, just not what you are expecting. The call is equivalent to

covmatrix(h1 = 1, h2 = 1)
covmatrix(h1 = 2, h2 = 2)

and so on.
The right way of calling the function for every combination of the two arguments is with outer .

outer(1:5, 1:5, covmatrix)
#            [,1]         [,2]         [,3]         [,4]        [,5]
#[1,] -0.41601317 -0.370097057 -0.124465470 -0.047267383  0.11745561
#[2,] -0.47072758 -0.272059262 -0.029614627  0.088643875  0.02381160
#[3,] -0.30116584 -0.258246136 -0.061882282  0.090978006 -0.05854558
#[4,] -0.08414056 -0.066622517  0.008072885 -0.035487867 -0.06632959
#[5,]  0.18854949 -0.003135701 -0.160137172  0.008353789 -0.18484782

Data generation code.

I will repeat the data generation code but this time setting the RNG seed.

set.seed(1234)
x <- arima.sim(n = 100, list(ar = 0.5))

Also, in the question you are missing n <- 100 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM