I'd like to transpose a time series dataset to feed into some machine learning algorithms. Here's an example of what I'd like to do, except the number of lags is large and I'm looking for a more elegant way to do it:
set.seed(42)
data <- data.frame(time = 1:5, value = rnorm(5))
data
# time value
# 1 1 1.3709584
# 2 2 -0.5646982
# 3 3 0.3631284
# 4 4 0.6328626
# 5 5 0.4042683
data %>%
mutate(lag_1 = lag(value),
lag_2 = lag(value, 2),
lag_3 = lag(value, 3),
lag_4 = lag(value, 4),
lag_5 = lag(value, 5))
# time value lag_1 lag_2 lag_3 lag_4 lag_5
# 1 1 1.3709584 NA NA NA NA NA
# 2 2 -0.5646982 1.3709584 NA NA NA NA
# 3 3 0.3631284 -0.5646982 1.3709584 NA NA NA
# 4 4 0.6328626 0.3631284 -0.5646982 1.3709584 NA NA
# 5 5 0.4042683 0.6328626 0.3631284 -0.5646982 1.370958 NA