R:如何在满足某些条件之前重复模拟时间序列数据

问题描述 投票:0回答:1

我想模拟随phi = 0.6跟随AR(1)的时间序列数据,这样,如果我尝试了第一次模拟,我将检查它是否遵循AR(1)。如果没有,我将进行第二次试验,与第一次试验一起,我将获得两次试验的平均值以形成系列。我会测试订单,直到它符合AR(1)为止,否则我会继续在试验中添加一(1),直到确认试验的平均值是AR(1)模型的时间序列。

之后,我将检查AR(1)的系数是否等于phi = 0.6。如果没有,我将在试验中添加一个(1),直到检查phi = 0.6。

** MWE *

library(FitAR)
n=50
a=0.6
count=0
e <- rnorm(n+100)
x <- double(n+100)
x[1] <- rnorm(1)
for(i in 2:(n+100)) {
  x[i] <- a * x[i-1] + e[i]
  }
x <- ts(x[-(1:100)])
p=SelectModel(x, lag.max = 14, Criterion = "BIC", Best=1)
if(p >= 2){
  count <- count + 1
  mat <- replicate(count, x)
  x <- as.ts(rowMeans(mat))
}
fit=arima(x,order = c(p,0,0))
my_coef=fit$coef
if(my_coef != 0.6){
  mat <- replicate(count + 1, x)
  x <- as.ts(rowMeans(mat))
}
my_coefficients=my_coef[!names(my_coef) == 'intercept']
print(my_coefficients)
print(paste0("AR(2) model count is: ", count_coef))
r replication arima
1个回答
0
投票

我们可以通过以下方式为零均值和标准差sd = 2的白噪声ARIMA(0,0,0)过程的100个时间点生成时间序列数据

set.seed(2020)
ts <- arima.sim(model = list(), n = 100, sd = 2)

这在文档?arima.sim中进行了解释

用法:

arima.sim(model, n, rand.gen = rnorm, innov = rand.gen(n, ...),
           n.start = NA, start.innov = rand.gen(n.start, ...),
           ...)

 ...: additional arguments for ‘rand.gen’.  Most usefully, the
      standard deviation of the innovations generated by ‘rnorm’
      can be specified by ‘sd’.

要生成50个时间序列,我们可以使用replicate

set.seed(2020)
mat <- replicate(50, arima.sim(model = list(), n = 100, sd = 2))

结果对象是尺寸为matrix100 x 50


我们可以确认标准偏差确实为sd = 2

summary(apply(mat, 2, sd))
# Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
#1.669   1.899   2.004   2.006   2.107   2.348
library(tidyverse)
apply(mat, 2, sd) %>%
    enframe() %>%
    ggplot(aes(value)) +
    geom_histogram(bins = 10)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.