1

I am trying to scatter plot two variables, one of which is the residuals from an lm() call. The xyplot() function will not do this scatter plot and returns the error message

Error in `[.xts`(y, id) : 'i' or 'j' out of range

The residuals are an xts variable and xyplot() can in fact still plot the residuals by itself (just a time plot, not a scatter plot).

Strangely, the work around I've found so far is to use as.xts() on the already xts residuals, or to use [ ,1] indexing to refer to the first column, even though there is only one column to begin with.

MWE is below, just looking for an explanation, thanks in advance.

library('lattice')
library('xts')
a = as.xts(ts(rnorm(20), start=c(1980,1), freq=4))
b = as.xts(ts(rnorm(20), start=c(1980,1), freq=4))

c = resid(lm(a~b))
str(c) # xts object

xyplot(c~a) # does not work: Error in `[.xts`(y, id) : 'i' or 'j' out of range
xyplot(c) # xyplot can plot it by itself just fine
xyplot(as.xts(c)~a) # works, if you use as.xts() on an xts object ?
xyplot(c[ ,1]~a) # works, if you refer to the 1st column of a 1 column object ? 
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
moof
  • 189
  • 9

1 Answers1

1

The problem is because c doesn't have a dim attribute, like most xts objects do, and how many xts functions expect xts objects to have. Set the dim attribute and everything's okay.

dim(c) <- c(length(c),1)
xyplot(c~a)
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418