I am trying to create a lagging vector inside an xts object using a function lag. It works when defining a new vector in an xts object using notation $(for example, x.ts$r1_lag), but when defining a new variable, square brackets are used, i.e. xts[,"r1_lag"]. See the following code:
library(xts)
x <- data.frame(date=seq(as.Date('2015-01-01'), by='days', length=100),
runif(1e2), runif(1e2), runif(1e2))
colnames(x) <- c("date", "r1", "r2", "r3")
x.ts <- xts(x, order.by=x$date)
x.ts$r1_lag <- lag(x.ts$r1)
x.ts <- xts(x, order.by=x$date)
x.ts[,"r1_lag"] <- lag(x.ts[,"r1"])
I need to use a notation []instead of a notation $to refer to vectors, because if I want to start the delay conversion in vectors in more than one xts object (vectors in a list of several xts objects), I cannot define new vectors inside objects using the notation $, those. I cannot define new vectors using the notation in the following stylized loop:
for (i in letters) {
for (j in variables) {
macro.set.ts$i$paste(j,"_L1",sep="") <- lag(macro.set.ts[[i]][,j])
macro.set.ts$i$paste(j,"_L2",sep="") <- lag(macro.set.ts[[i]][,j], 2)
macro.set.ts$i$paste(j,"_L4",sep="") <- lag(macro.set.ts[[i]][,j], 4)
}
}
Thank!