Reputation: 1480
I have data frame which I lag a number of times as to create an incremental lagged data frame having the same length.
library(quatmod)
x<-c(1,2,3,4,6,7,4,2,3,4,3,4,6,7,7,8,9,0,0,9,7,6,4,5,3,2,3,2,3,4,5,6,7,8,8,9,9)
x1<-na.omit(Lag(x,1))
x2<-na.omit(Lag(x,2))
x3<-na.omit(Lag(x,3))
x4<-na.omit(Lag(x,4))
x5<-na.omit(Lag(x,5))
x6<-na.omit(Lag(x,6))
x7<-na.omit(Lag(x,7))
short<-min(length(x1),length(x2),length(x3),length(x4),length(x5),length(x6),length(x7))
x1<-tail(x1,short)
x2<-tail(x2,short)
x3<-tail(x3,short)
x4<-tail(x4,short)
x5<-tail(x5,short)
x6<-tail(x6,short)
x7<-tail(x7,short)
xlag<-data.frame(x1,x2,x3,x4,x5,x6,x7)
I am wondering if this expressions could be made more efficient via a function
Thanks
Upvotes: 0
Views: 86
Reputation: 3188
Let n be your max lag. Your code can reduced to one line.
xlag = tail(Lag(x, 1:n), length(x)-n)
Upvotes: 1
Reputation: 378
What about this:
maxlag <- 7;
sapply(maxlag:1, function(i) x[i:(i+(length(x)-maxlag-1))])
Or if your maximal lag and the length of x
are static, even simpler:
sapply(7:1, function(i) x[i:(i+29)])
Upvotes: 1