gpt4 book ai didi

r - arima.sim() 函数具有不同的 : sample sizes, phi 值和 sd 值

转载 作者:行者123 更新时间:2023-12-04 15:32:23 25 4
gpt4 key购买 nike

我想用不同的方式模拟 ARIMA(1,1,0):

  1. 样本量
  2. phi 值
  3. 标准偏差值。

我很欣赏下面的 r 代码是如何模拟一个 ARIMA(1,1,0) 我想按照格式来模拟许多 ARIMA (1,1,0) 具有不同的样本大小phi 值标准差值

wn <- rnorm(10, mean = 0, sd = 1)
ar <- wn[1:2]
for (i in 3:10){
ar<- arima.sim(n=10,model=list(ar=-0.7048,order=c(1,1,0)),start.innov=4.1,n.start=1,innov=wn)
}

我问过类似的问题here并根据我的问题给出了一个很好的答案,但现在我看到 arima.sim() 函数在模拟 ARIMA 时间序列中是不可或缺的,因此想将它合并到我的模拟 ARIMA 时间序列的风格。我想出了这个试验,它使用 arima.sim() 函数来模拟 N=c(15, 20) ARIMA(1,1,0) 具有不同样本大小标准差值phi 值 的时间序列,首先生成N 随机数然后使用初始的两个随机数作为前两个 ARIMA(1,1,0)。第 3 到 **n** 是遵循ARIMA(1,1,0)`。这是我在下面尝试过的:

N <- c(15L, 20L)
SD = c(1, 2) ^ 2
phi = c(0.2, 0.4)
res <- vector('list', length(N))
names(res) <- paste('N', N, sep = '_')
set.seed(123L)
for (i in seq_along(N)){
res[[i]] <- vector('list', length(SD))
names(res[[i]]) <- paste('SD', SD, sep = '_')
ma <- matrix(NA_real_, nrow = N[i], ncol = length(phi))
for (j in seq_along(SD)){
wn <- rnorm(N[i], mean = 0, sd = SD[j])
ar[[1:2, ]] <- wn[[1:2]]
for (k in 3:N[i]){
ar[k, ] <- arima.sim(n=N[[i]],model=list(ar=phi[[k]],order=c(1,1,0)),start.innov=4.1,n.start=1,innov=wn)
}
colnames(ar) <- paste('ar_theta', phi, sep = '_')
res[[i]][[j]] <- ar
}
}
res1 <- lapply(res, function(dat) do.call(cbind, dat))
sapply(names(res1), function(nm) write.csv(res1[[nm]],
file = paste0(nm, ".csv"), row.names = FALSE, quote = FALSE))

最后两行将时序数据写入.csv,保存在我的工作目录下。

最佳答案

这里可能是一个使用Map的方法。如果这不符合您的要求,请编辑您的帖子以包含预期输出。

N <- c(15L, 20L)
SD <- c(1, 2) ^ 2
phi = c(0.2, 0.4)

## generate all combos
all_combos <- expand.grid(N = N, SD = SD, phi = phi)

## create function
fx_arima <- function(n, SD, phi) {
arima.sim(n = n,
model=list(ar=phi, order = c(1, 1, 0)),
start.innov = 4.1,
n.start = 1,
rand.gen = function(n) rnorm(n, mean = 0, sd = SD))[-1L]
}

## find arima for all combos using Map
set.seed(123L)
res = Map(fx_arima, all_combos[["N"]], all_combos[["SD"]], all_combos[["phi"]])

## or a little bit more work:
set.seed(123L)
res2 = by(all_combos, all_combos["N"],
function(DF) {
res = mapply(fx_arima, DF[["N"]], DF[["SD"]], DF[["phi"]])
colnames(res) = paste("SD", DF[["SD"]], "phi", DF[["phi"]], sep = "_")
res
})
res2

## write to csv
Map(function(file, DF) write.csv(DF, paste0("N_", file, ".csv")), names(res2), res2)

关于r - arima.sim() 函数具有不同的 : sample sizes, phi 值和 sd 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60970948/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com