1

Suppose that I have the following "for" loop in R.

USDlogreturns=diff(log(prices))

for(i in 0:5){
  for(j in 0:5){
    fit <- arima(USDlogreturns, order=c(i,0,j), include.mean=TRUE)
     }
}

How do you tell R to substitute a NA matrix with the coefficients of all the estimated models?

msmna93
  • 41
  • 6
  • I have many related questions on this kind of use of for loops. So I would appreciate any kind help to provide me with the commands that I need. – msmna93 Oct 14 '16 at 21:19

1 Answers1

1

You will need a matrix M with dimensions 36 times 13. Then use

M=matrix(NA,36,13)
k=0 # current row being filled in
for(i in 0:5){
  for(j in 0:5){
    k=k+1
    fit <- arima(USDlogreturns, order=c(i,0,j), include.mean=TRUE)
    if(i>0) M[k,c(1:   i) ]=fit$coef[c(   1 :   i )] # AR coefficients in the 2nd-6th columns
    if(j>0) M[k,c(8:(7+j))]=fit$coef[c((i+1):(i+j))] # MA coefficients in the 8th-12th columns
            M[k,      13  ]=tail(fit$coef,1)         # "intercept" (actually, mean) in the 13th column
  }
}

The columns 2 to 6 will contain AR coefficients.
The columns 8 to 12 will contain MA coefficients.
The 13th column will contain the "intercepts" (actually, the means, as the terminology in the arima function is misleading).

Richard Hardy
  • 375
  • 6
  • 20
  • Yes, I know the built-in terminology is sometimes misleading. Thank you a lot for your answer. – msmna93 Oct 15 '16 at 13:47
  • I do not know why I run the above code and got this error message. Error in tail(fit@coef, 1) : trying to get slot "coef" from an object (class "Arima") that is not an S4 object > – msmna93 Oct 15 '16 at 14:12
  • No problem, I was also getting there. But rerunning the new code, I get this new error message: Error in M[k, 13] = tail(fit$coef, 1) : object "M" not found – msmna93 Oct 15 '16 at 14:19
  • Last question I have on the topic. Suppose that I want to loop also for a third variable z (TRUE/FALSE with respect to the arima function argument include.mean). After creating the related vector, how do you insert the third array dimension into the if command? – msmna93 Oct 15 '16 at 14:47
  • A two-dimensional matrix is sufficient. Just add another column in the matrix for storing the coefficient values of that variable, and add another loop inside the inner loop to alternate between TRUE and FALSE. – Richard Hardy Oct 15 '16 at 14:54