gpt4 book ai didi

r - 通过具体示例了解 R 循环中的迭代编码

转载 作者:行者123 更新时间:2023-12-01 09:18:39 25 4
gpt4 key购买 nike

尽管粘贴的代码很长,但这个问题可能非常基础,并且与我在 R 中使用循环的困难有关。

关于 this youtube video 的评论在 ARMA(1,1) 过程中,评论者提供了 R 中的模拟。我认为对于我的问题,直接转到 ARMA 函数的 # Moving-average component 是可以的:

ARMA = function(phi, theta, n = 100, init = 0, burn = 0)
{
m = n + burn # Optional burn-in
z = rnorm(m) # White noise sample

x = init
for (i in 2:m) # Generate the time series
{
# Autoregression component

p = min(length(x), length(phi)) # Prevent out-of-bounds
AR = sum(phi[1:p] * x[1:p])

# Moving-average component

q = min(i - 1, length(theta)) # Prevent out-of-bounds
MA = sum(theta[1:q] * z[(i - 1):(i - q)])

# Combined AR+MA component

new = AR + MA + z[i]
x = c(new, x) # x is built in reverse
}

# Truncate the burn-in
# Re-reverse x vector
# Return time series

ts(rev(x[1:n]))
}

plot(ARMA(0.3, 0.2))

q = min(i - 1, length(theta)) 对我来说看起来像是一个常数,因为无论 i 迭代次数是多少(而且我们从 2 开始,所以 i - 11 及以上),i - 1 将始终相等(在在 1) 或大于 length(theta) 的情况下,theta 是一个常数(因此 length(theta) = 1)。因此 q,即 min 将始终为 1

因此,我不理解sum(theta[1:q] * z[(i - 1):(i - q)])z[(i - 1):(i - q)] 将是 z[(i - 1):(i - 1)],即 z[i]theta[1:q] 将是 theta[1],这没有意义,因为 theta 只有一个值,除非 theta 是一个向量。但事实是,我可以使用单个 theta 值运行 ARMA

我错过了什么?

最佳答案

您可以运行 ARMA,因为 n 等于 100 并且循环产生 2:m(在本例中为 99)个值。每个 1:99 都与 theta 相乘,得到 99 个不同的值 (MA = sum(theta[1:q] * z[(i - 1):(i - q)]))。 z[(i - 1):(i - q)]) 不等于 z[i]z[i-1]而 theta 的长度为 1。

关于r - 通过具体示例了解 R 循环中的迭代编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33967082/

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