xts already allows this. Look at Section 4 of the package vignette.
Basically, you call try.xts
at the beginning of your function and reclass
at the end. I use this paradigm in the TTR package. For example:
R> momentum
function (x, n = 1, na.pad = TRUE)
{
x <- try.xts(x, error = as.matrix)
if (is.xts(x)) {
mom <- diff(x, n, na.pad = na.pad)
}
else {
NAs <- NULL
if (na.pad) {
NAs <- rep(NA, n)
}
mom <- c(NAs, diff(x, n))
}
reclass(mom, x)
}
<environment: namespace:TTR>