重复的滞后更容易在
data.table
作为
shift
可以取向量
n
S
library(data.table)
# create a vector of new column names
nm1 <- paste0(rep(names(a), each = length(params)), '_run', params)
# get the `shift` of the Subset of Data.table (`.SD`)
# by default type is "lag"
# assign the output to the column names created earlier
setDT(a)[, (nm1) := shift(.SD, n = params)] a
# val1 val2 val1_run1 val1_run2 val1_run3 val2_run1 val2_run2 val2_run3
#1: 10 20 NA NA NA NA NA NA
#2: 11 21 10 NA NA 20 NA NA
#3: 12 22 11 10 NA 21 20 NA
#4: 13 23 12 11 10 22 21 20
#5: 14 24 13 12 11 23 22 21
#6: 15 25 14 13 12 24 23 22
或者使用
tidyverse
具有
parse_exprs
library(tidyverse)
library(rlang)
# create a string with `rep` and `paste`
nm2 <- glue::glue('lag({rep(names(a), each = length(params))}, n = {rep(params, length(a))})') %>% paste(., collapse=";")
# convert string to expression with parse_exprs and evaluate (`!!!`)
a %>%
mutate(!!! parse_exprs(nm2)) %>%
rename_at(-(1:2), ~nm1)
# A tibble: 6 x 8
# val1 val2 val1_run1 val1_run2 val1_run3 val2_run1 val2_run2 val2_run3
# <int> <int> <int> <int> <int> <int> <int> <int>
#1 10 20 NA NA NA NA NA NA
#2 11 21 10 NA NA 20 NA NA
#3 12 22 11 10 NA 21 20 NA
#4 13 23 12 11 10 22 21 20
#5 14 24 13 12 11 23 22 21
#6 15 25 14 13 12 24 23 22