I try to run the following piece of code in the book Data Mining with R
yearlyReturn(trade.res@trading$Equity)
Error in NextMethod("[<-") : incorrect number of subscripts on matrix The error actually occurs when executing the PeriodReturn that is called by yearlyReturn. The instruction that caused the problem is:
ret[1,] <- firstval
## periodReturn()
xx <- try.xts(x)
if (inherits(x, "ts")) {
x <- na.omit(try.xts(x))
xtsAttributes(x) <- CLASS(x) <- NULL
xx <- x
TS <- TRUE
}
else TS <- FALSE
if (has.Op(xx) & has.Cl(xx)) {
getFirst <- function(X) Op(X)
getLast <- function(X) Cl(X)
}
else getFirst <- getLast <- function(X) X[, 1]
on.opts <- list(daily = "days", weekly = "weeks", monthly = "months",
quarterly = "quarters", yearly = "years", annually = "years")
ep <- endpoints(xx, on = on.opts[[period]])
ret <- Delt_(Cl(to_period(xx, period = on.opts[[period]],
...)), type = type)
if (leading) {
firstval <- as.numeric(Delt_(getFirst(xx[1]), getLast(xx[ep[2]]),
type = type))
ret[1, ] <- firstval
}
colnames(ret) <- paste(period, "returns", sep = ".")
if (TS)
xx <- 1
tmp.ret <- reclass(ret, xx[ep[-1]])
if (is.null(subset))
subset <- "/"
reclass(as.xts(tmp.ret)[subset])
}