我需要为模拟研究生成自回归时间序列。最终我需要以嵌套的方式在许多 block 上执行此操作。我以为我可以使用 mutate()
和 lag()
轻松实现这一点,但显然不是:
# Initialise some data
trial.data = tibble(
trial = rep(1:20, times = 1),
y = 1
)
# Replace y values with a new autoregressed value in each row
trial.data %>%
rowwise() %>%
mutate(y = lag(y, default = 1)*0.8)
# A tibble: 10 x 2
# Rowwise:
trial y
<int> <dbl>
1 1 0.8
2 2 0.8
3 3 0.8
4 4 0.8
5 5 0.8
6 6 0.8
7 7 0.8
8 8 0.8
9 9 0.8
10 10 0.8
我使用 for 循环得到了预期的结果:
for (i in 2:10) {
trial.data$y[i] <- trial.data$y[i-1]*0.8
}
trial.data
# A tibble: 10 x 2
trial y
<int> <dbl>
1 1 1
2 2 0.8
3 3 0.64
4 4 0.512
5 5 0.410
6 6 0.328
7 7 0.262
8 8 0.210
9 9 0.168
10 10 0.134
任何关于如何在 dplyr 管道中执行此操作的提示将不胜感激...我的另一个想法是功能化我的 for 循环,但这不起作用:
loop_fun <- function(x) {
for (i in 2:10) {
x[i] <- x[i-1]*0.8
}
}
trial.data %>%
mutate(y2 = loop_fun(y))
最佳答案
您可以使用accumulate
进行此类递归计算。
library(dplyr)
library(purrr)
trial.data %>% mutate(y = accumulate(y, ~.x * 0.8))
# trial y
# <int> <dbl>
# 1 1 1
# 2 2 0.8
# 3 3 0.64
# 4 4 0.512
# 5 5 0.410
# 6 6 0.328
# 7 7 0.262
# 8 8 0.210
# 9 9 0.168
#10 10 0.134
#11 11 0.107
#12 12 0.0859
#13 13 0.0687
#14 14 0.0550
#15 15 0.0440
#16 16 0.0352
#17 17 0.0281
#18 18 0.0225
#19 19 0.0180
#20 20 0.0144
在基础 R 中使用 Reduce
。
trial.data$y <- Reduce(function(x, y) x * 0.8, trial.data$y, accumulate = TRUE)
关于r - 有没有 dplyr 方法来生成 AR(1) 时间序列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68326276/