Question

After using the lag function on a multi variable zoo object, new variables are created with an automatic naming convention that uses a hyphen. For example, lags of the variable var2 will be named as var2.lag-4 and so on. The problem is that when I want to refer to this variable, such as in plot(var2.lag-4) it returns the error message object var2.lag not found

I presume this is because it sees the hyphen sign as a subtraction sign between one variable name and the scalar number 4.

Is it possible to refer to these lagged zoo variables without this error?

Note that I have also attached the object, so that variable names can be used directly.

Here is an example

var1 = ts(rnorm(20), start=1995.00, freq=4)
var2 = ts(rnorm(20), start=1995.00, freq=4)
X = cbind(var1, var2) 
newX = lag(as.zoo(X),-1:-4) # lags 1 to 4 of all variables
attach(as.list(newX))
plot(var2.lag-1) 
#Error in plot.window(...) : need finite 'ylim' values
#In addition: Warning messages:
#1: In xy.coords(x, y, xlabel, ylabel, log) : NAs introduced by coercion
#2: In min(x) : no non-missing arguments to min; returning Inf
#3: In max(x) : no non-missing arguments to max; returning -Inf
Was it helpful?

Solution 2

If k has names, those will be used to create the new column names. So you could add names to the vector you pass to k:

k <- -1:-4
# make.names will ensure the column names are syntactically valid
names(k) <- make.names(paste0("lag",k))
newX <- lag(as.zoo(X), k)

And plot doesn't know what to do with character strings. You have to pass it an object to plot.

plot(newX$var2.lag.1)

OTHER TIPS

You have to tell plot that the string is a name of a column of newX:

plot(newX[ , "var2.lag-1"])

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top