问题
This is a question to continue from this (R: Recreate historical membership from a list of changes in membership) question.
The problem discussed there actually arises from a problem of general interest in finance where we typically have member stocks of an index and then changes in the index membership. Often we want to recreate this membership and the data at hand is the current membership and the dates of the changes with the changes.
However, the typical problem is to generate this membership for a regular time series (such as daily, weekly, etc.) while the changes are themselves an irregular time series.
The method suggested in the problem linked to above can be used here in such a fashion:
- Find membership at all known times of changes.
- Create a sequence of a favored time class at the desired frequency.
- Replicate membership for each time in the sequence using the last known change in membership.
I will like to write function methods for the recreate.memship
function that can do the right thing for indx
given in any time-series class in R. One way that I can think of is to define a method for each known class such as ts
, Date
, zoo
, xts
, ... for which a seq
method exists.
The question after this long-winded discussion is two-fold:
- Is there a smart way of defining methods such that I don't have to write a new method for each known time class. (Paraphrasing, how will a programmer smarter than me design this?)
- Is there a known solution for this problem / class of problems?
回答1:
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>
来源:https://stackoverflow.com/questions/17569577/create-a-function-method-for-all-possible-time-series-classes