-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlags.R
40 lines (36 loc) · 1.15 KB
/
lags.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#====================================================================#
# Author: Damian Gwozdz (DG)
# Function: lags
# Creation date: 31AUG2017
# Last modified: -
# Description: Function to add lags of selected variables
# to the given dataset
# Required functions: -
#
#====================================================================#
lags <- function(dset, vars, lag.vec){
#====================================================================
# PARAMETERS:
#
# 1) dset - input data set
# 2) vars - vector of variables names
# 3) lag.vec - vector of lags
#
# EXAMPLE:
#
# iris2 <- lags(iris, c("Sepal.Length"), c(3, 5, 7))
#
#====================================================================
## Parameters for tests
# dset <- iris
# vars <- c("Sepal.Length", "Sepal.Width")
# lag.vec <- c(3,5)
for(i in 1:length(vars)){
for(j in 1:length(lag.vec)){
dset[[paste0(vars[i], ".", lag.vec[j])]] <-
c(rep(NA, times = lag.vec[j]),
dset[[vars[i]]][(-(length(dset[[vars[i]]]))+lag.vec[j]-1):-length(dset[[vars[i]]])])
}
}
return(dset)
}