Barnaby
Barnaby

Reputation: 1480

General expression for creating an equal length lag dataframe

I have a vector and run the following autocorrelation function where I obtain the significant lags and create a dataframe adjusted to the minimun length of the lags. The example produces random numbers and thus it maybe necessary to repeat the code so enough lagged variables occur.

   L library(quantmod)

x <- filter(rnorm(100), filter=rep(1,3), circular=TRUE)   

a<-acf(x)
b<-a[[1]]   
c<-(b[2:length(b)])
posssignificance_level<-qnorm((1+0.95)/2)/sqrt(sum(!is.na(x)))
negsignificance_level<- -posssignificance_level
poscorr<-which(posssignificance_level<c)
negcorr<-which(negsignificance_level>c)
L<-(sort(c(poscorr,negcorr)))

#[1] 1  2  8  9 10


#Create lagged versions of x 
W1 <- na.omit (Lag(x, L[1]))
W2 <- na.omit (Lag(x, L[2]))
W3 <- na.omit (Lag(x, L[3]))
W4 <- na.omit (Lag(x, L[4]))
W5 <- na.omit (Lag(x, L[5]))


#make all laged versions equal in length 
shortest <-min(length(W1),length(W2),length(W3),length(W4),length(W5))
W1<-tail(W1, shortest)
W2<-tail(W2, shortest)
W3<-tail(W3, shortest)
W4<-tail(W4, shortest)
W5<-tail(W5, shortest)

#create data frame
df<-data.frame(W1,W2,W3,W4,W5)

Is there a more efficient and maybe a general way to do #Create lagged versions of x and #make all laged versions equal in length as to create a dataframe provided that if x numbers are changed the length of L may also change (the number of objects (W1,W2...) may also change)

Thank you

Upvotes: 0

Views: 39

Answers (1)

Jota
Jota

Reputation: 17621

Here is a way to do what you're doing without needing to know the length of L. In your example all the lagged versions are equal in length (100 observations), but this should work if they are not:

# create lagged version
Wlist <- lapply(seq_along(L), function(ii) na.omit(Lag(x, L[ii])))
# find shortest
shortest <- Reduce(min, lapply(Wlist, function(x) length(x)))
# create data frame and make all lagged versions equal in length
data.frame(do.call(cbind, lapply(Wlist, tail, shortest)))

Upvotes: 1

Related Questions