-2

I have a matrix of ts values and i need to save all garch models (models construct for each column af a matrix) in a list. I tried this code and it doesn't work (i can't understand why):

model = list()
for (i in ncol(p)) {
  if (length(model) == 0) {
      model = list(ugarchfit(data=p[-1,i], spec=spec))
  } else {
      bufer = ugarchfit(data=p[-1,i], spec=spec)
      model = cbind(model, bufer)
  }
}

Can somebody help me to cope with this? I need to address this list with the column index and get a model for this column index. Thanks!

gevorg
  • 4,835
  • 4
  • 35
  • 52
N.Chuk
  • 1

1 Answers1

2

It is better the create the list with final dimensions rather that to create a growing list.

models <- vector("list", ncol(p))

Then overwrite the relevant element of the list

for (i in seq_len(ncol(p))) {
  models[[i]] <- ugarchfit(data = p[-1, i], spec = spec)
}

Another solution would to use lapply

models <- lapply(
  seq_len(ncol(p)),
  function(i) {
    ugarchfit(data = p[-1, i], spec = spec)
  }
)

Note that your code will be more clear is you use = for passing arguments to a function and <- for assignments.

Thierry
  • 18,049
  • 5
  • 48
  • 66