Reputation: 63
I got a piece of R code shown as below to find out the values of Y in the last row , each time I run it, R will give 100 values of Y because I set N= 100 as beginning of the simulation...
I am going to simulate it for 500 times to find 500 series of Y. Each simulation contains 100 Y values. As a result, I want to get something like a matrix with 500 rows of simulation, each row contains 100 Y values. I suppose a for loop will help but I did not figure out how to do it? Could anyone help please? Many thanks!!!!!!
N = 100
# set up initial values
alpha1 = 8.439e-02
beta1 = 8.352e-01
mu = 7.483e-03
omega = 1.343e-04
X_0 = -3.092031e-02
sigma_0 = 0.03573968
eps = rt (N,7.433e+00)
# loops
Xn= numeric (N)
sigma= numeric (N)
sigma[1] = sigma_0
Xn[1] = X_0
for (t in 2:N){
sigma[t] = sqrt (omega + alpha1 * (Xn[t-1])^2 + beta1* (sigma[t-1])^2)
Xn[t] = sigma[t] * eps[t]
}
Y = mu + Xn
head(Y)
Upvotes: 1
Views: 747
Reputation: 12559
Put all that in a function getY <- function(N) { ... }
and use replicate(500, getY(100))
. So you can do:
getY <- function(N) {
# set up initial values
alpha1 <- 8.439e-02
beta1 <- 8.352e-01
mu <- 7.483e-03
omega <- 1.343e-04
X_0 <- -3.092031e-02
sigma_0 <- 0.03573968
eps <- rt(N, 7.433e+00)
# loops
Xn <- numeric (N)
sigma <- numeric (N)
sigma[1] <- sigma_0
Xn[1] <- X_0
for (t in 2:N) {
sigma[t] <- sqrt (omega + alpha1 * (Xn[t-1])^2 + beta1* sigma[t-1])^2)
Xn[t] <- sigma[t] * eps[t]
}
Y <- mu + Xn
}
X <- replicate(500, getY(100))
If you want, you can transpose the result with t()
, i.e.
X <- t(replicate(500, getY(100)))
Upvotes: 1