Warhawk1987
Warhawk1987

Reputation: 307

Creating simulations out of a function with n number of observations

I'm pretty new to R and I have created the following code which is based on a function that is used to simulate 1100 data points and then removes the first 100 points to get a total of 1000 data points.

My next goal is to be able to repeat this process 250 times so I have 250 simulations each with 1000 data points. I'm thinking that another for statement would work but I am not 100% sure how I would set up the iteration process for a loop within a loop.

I've provided my sample code below that produces 1000 observations.

Thank you for the help.

e<-rnorm(1100, mean=0, sd=0.2) # sd=0.2 is the default used in the paper.
Y_t=c(0,0)
for (i in 3:length(e)){
  f1<- 0.138+(0.316+0.982*Y_t[i-1])*exp(-3.89*(Y_t[i-1])^2)
  f2<- -0.437-(0.659+1260*Y_t[i-1])*exp(-3.89*(Y_t[i-1])^2)
  Y_t[i]<-f1*Y_t[i-1]+f2*Y_t[i-2]+e[i]
}
Y_t<-Y_t[101:1100] # Remove the first 100 observations

Upvotes: 1

Views: 302

Answers (1)

GuedesBF
GuedesBF

Reputation: 9878

We can create a user-defined function that includes all your code, then call it in a loop (I used lapply here)


sampler<-function(){     # new function wrap around your original code
e<-rnorm(1100, mean=0, sd=0.2)
Y_t<-c(0,0)
for (i in 3:length(e)){
        f1<- 0.138+(0.316+0.982*Y_t[i-1])*exp(-3.89*(Y_t[i-1])^2)
        f2<- -0.437-(0.659+1260*Y_t[i-1])*exp(-3.89*(Y_t[i-1])^2)
        Y_t[i]<-f1*Y_t[i-1]+f2*Y_t[i-2]+e[i]
}
Y_t<-Y_t[101:1100]
Y_t         #return the final object
}

lapply(1:250, function(x) sampler())

If you want the output to be a data.frame with 250 columns, one for each simulation, you can cbind the output of lapply or use purrr::map_dfc. There are methods for outputing lists or matrixes too (replicate).

library(purrr)

map_dfc(1:250, ~sampler())   #output is a data.frame

# OR

replicate(250, sampler())  #output is a matrix, becomes a list if include simplify=FALSE

example output

map_dfc(1:2, ~sampler())

# A tibble: 1,000 x 2
      ...1   ...2
     <dbl>  <dbl>
 1 -82.0   -79.8 
 2 116.    113.  
 3  51.7    50.9 
 4 -43.5   -42.8 
 5 -28.4   -27.8 
 6  14.9    15.1 
 7  14.4    14.3 
 8  -4.23   -4.69
 9  -6.65   -6.74
10   0.922   1.03
# … with 990 more rows

Upvotes: 1

Related Questions