从具有 n 个观察值的函数创建模拟

Creating simulations out of a function with n number of observations

我是 R 的新手,我创建了以下代码,该代码基于用于模拟 1100 个数据点的函数,然后删除前 100 个点以获得总共 1000 个数据点。

我的下一个目标是能够重复这个过程 250 次,这样我就有 250 个模拟,每个模拟有 1000 个数据点。我认为另一个 for 语句可以工作,但我不是 100% 确定我将如何为循环中的循环设置迭代过程。

我在下面提供了生成 1000 个观测值的示例代码。

感谢您的帮助。

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

我们可以创建一个包含您所有代码的用户定义函数,然后在循环中调用它(我在这里使用 lapply)


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())

如果您希望输出为具有 250 列的 data.frame,每个模拟一列,您可以绑定 lapply 的输出或使用 purrr::map_dfc。也有输出列表或矩阵的方法(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

示例输出

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