Hyun. J - 6 months ago 43
R Question

# R programming (function and time series index)

I'm programming with using R.

and I have to make function and for loop.

Value : t=0.001, n=4 and functions attached below.

I want to calculate y2(0.001), y3(0.001) and y4(0.001) by using for loop.

Also, I made a R code, but there is a error that I don't know.

How can I made for loop to calculate y2(0.001), y3(0.001) and y4(0.001)?

And below code is my R code. Thank You.

``````###########################
#   value                 #
###########################
n<-4
t<-0.001
sigma<-numeric(4)
y<-numeric(4)
sigma[1]<-0.1
y[1]<-0

###########################
#   Brownian-Motion       #
###########################
nor1<-rnorm(n,0,1)
nor1<-cumsum(nor1)

###########################
#   function              #
###########################
delta<-function(t){
0.01
}
alpha<-function(t){
2*t*(1-t)
}
beta<-function(t){
2*t*(1-t)
}
epsilon<-function(t){
(2^(200*t))*(nor1)*(1/sqrt(log10(2)))
}

###########################
#   for-loop              #
###########################
sigma[i]<-delta(t)+(alpha(t)*y[i-1]*y[i-1])+(beta(t)*sigma[i-1]sigma[i-1]);
y[i]<-sigma[i]*epsilon(t);
print(y[i])
}
``````

There are couple of things I would polish (comment if you want more details), but your besides point made by @Prem, you had wrongly specified the for loop as such (maybe run through a tutorial on loops in R) and the sigma multiplication.

But mostly, the epsilon function returned a vector - a value for each observations - instead of a single value. So I fixed it to be dependent on `i` as is in 2).

``````epsilon<-function(t,i){
(2^(200*t))*(nor1[i])*(1/sqrt(log10(2)))
}
``````

Then the for loop works as such:

``````for (i in 2:n){
sigma[i]<-delta(t)+(alpha(t)*y[i-1]*y[i-1])+(beta(t)*sigma[i-1]*sigma[i-1]);
y[i]<-sigma[i]*epsilon(t,i);
print(y[i])
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download