1

I am using tick data to convert it into minutes interval

test <- to.minutes(x, OHLC=TRUE)
colnames(test) <- c("Open","High","Low","Close")
test
2011-06-07 14:23:00  435  435  435  435   
2011-06-07 14:26:00  430  435  430  435   
2011-06-07 14:32:00  435  435  430  430   
2011-06-07 14:35:00  430  430  430  430 
str(test)

  An ‘xts’ object from 2011-03-10 to 2011-06-08 23:56:00 containing:
  Data: num [1:20426, 1:4] 350 360 375 375 370 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:4] "Open" "High" "Low" "Close"
  Indexed by objects of class: [POSIXct,POSIXt] TZ: 
  xts Attributes:  
 NULL

now I try to use rollapply as follows:

test1<-rollapply(test, width=20, FUN=function(x) {x$xt <-seq(1-nrow(x),0); lm(Close ~poly(xt,4),x)}, by.column=FALSE, align="right")

but that generates

    Error in eval(expr, envir, enclos) : object 'Close' not found
In addition: Warning message:
In x$xt <- seq(1 - nrow(x), 0) : Coercing LHS to a list
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
user1155299
  • 877
  • 5
  • 20
  • 29

1 Answers1

4

Please start providing reproducible examples. Here's an example reproducible example:

library(xts)
data(sample_matrix)
test <- as.xts(sample_matrix)

myFun <- function(x) {
  x$xt <- seq(1-nrow(x),0)
  lm(Close ~ poly(xt,4), data=x)
}
test1 <- rollapplyr(test, width=20, FUN=myFun, by.column=FALSE)

The warning is a good hint. Look at the source of zoo:::rollapply.zoo and you'll see that it runs your function on coredata(your_data), which is a matrix. The $ function doesn't work for matrix subsetting, so you would need to use cbind instead.

But lm needs a data.frame, not a matrix, so do that:

myFun2 <- function(x) {
  x <- data.frame(x, xt=seq(1-nrow(x), 0))
  lm(Close ~ poly(xt,4), x)
}
test1 <- rollapplyr(test, width=20, FUN=myFun2, by.column=FALSE)
Community
  • 1
  • 1
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
  • thanks Joshua, I will follow the guidelines for my next post. – user1155299 Jan 24 '12 at 17:23
  • @user1155299: there's no warning, so I don't know what you're referring to. I can't replicate your error, but I get a different error: "Error in zoo(rval, index(x)[i]): “x” : attempt to define invalid zoo object". `?confint` says the function expects a "fitted model object". You're passing it a "zoo" object, so I'm not surprised it throws an error. It seems like you might need to step back and re-think how you're approaching your problem. – Joshua Ulrich Jan 24 '12 at 19:52
  • I had made an error, so I removed the post, but you were quick in catching it ;-) – user1155299 Jan 24 '12 at 21:06