我正在寻找一种方法来生成从具有动态位置数(参数n)的滞后列派生的列,这意味着这个新列应该将n存储在另一列中的值作为参数(请参阅lag函数文档)。
样本数据:
set.seed(42)
df <- as_tibble(data.frame(
id = c(rep(1,6), rep(2,5), rep(3,6)),
n_steps = c(0,0,0,0,1,2,0,0,1:3,0,1:5),
var1 = sample(1:9, 17, replace = TRUE),
var2 = runif(17, 1, 2)))
# A tibble: 17 x 4
id n_steps var1 var2
<dbl> <dbl> <int> <dbl>
1 1 0 1 1.08
2 1 0 5 1.51
3 1 0 1 1.39
4 1 0 9 1.91
5 1 1 4 1.45
6 1 2 2 1.84
7 2 0 1 …Run Code Online (Sandbox Code Playgroud)