At first step, I want to generate a series (more specifically; GARCH (1, 1)), and the estimated it with four different estimation methods (let’s say, M1, M2, M3, M4). In addition, I want to **repeat this process over 6000 times with saving results of each repetition.
I have done it one by one, but unable to construct a loop.
We don't really have enough info to help you out. Could you ask this with a minimal REPR oducible EX ample (reprex)? A reprex makes it much easier for others to understand your issue and figure out how to help.
"Growing" a vector can dramatically slow down code. How much depends on the code, but it's better to avoid it all the time. If you know the "sizes" of the result, create an object with those sizes and fill it in as you go.
results <- vector("list", 6000)
for (counter in seq_along(results)) {
results[[counter]] <- estimate_GARCH_parameters_by_four_methods(...)
}
A for loop is good for "complex" logic inside the loop. If the steps are just function calls, lapply() would be "R idiomatic." But, here, the code depends on the logic. So more details are needed.
It depends on what's actually being done. If there really is a function like estimate_GARCH_parameters_by_four_methods(...), then lapply() is a great solution.
But if there isn't, then lapply() often won't simplify code. For example:
results <- vector("list", 6000)
for (ii in seq_along(results)) {
# A whole bunch of prep logic
m1 <- estimate_GARCH_parameters_m1(...)
m2 <- estimate_GARCH_parameters_m2(...)
m3 <- estimate_GARCH_parameters_m3(...)
m4 <- estimate_GARCH_parameters_m4(...)
results[[ii]] <- list(m1, m2, m3, m4)
}
Writing a wrapper function and feeding it to lapply() won't clarify this code.
The for block is obviously just an iterative loop, where the 1:6000 vector might be irrelevant. The lapply() code makes the 1:6000 vector seem important.