I need to generate an autoregressive timeseries for a simulation study. Ultimately I will need to do this in a nested fashion over many blocks. I thought I could easily achieve this using mutate() and lag() but apparently not:
# 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
I get the expected result using a for loop:
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
Any hints how to do this in a dplyr pipe would be appreciated... One further thought I had was to functionalize my for loop but this doesn't work:
loop_fun <- function(x) {
for (i in 2:10) {
x[i] <- x[i-1]*0.8
}
}
trial.data %>%
mutate(y2 = loop_fun(y))