为所有可能的时间序列类创建一个函数方法 [英] Create a function method for all possible time series classes

查看:111
本文介绍了为所有可能的时间序列类创建一个函数方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是从此继续的问题(解决方案

xts已经允许了此功能.请参见包装插图的第4部分. >

基本上,您在函数的开头调用try.xts,在函数的结尾调用reclass.我在TTR包中使用了这种范例.例如:

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>

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:

  1. Find membership at all known times of changes.
  2. Create a sequence of a favored time class at the desired frequency.
  3. 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:

  1. 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?)
  2. Is there a known solution for this problem / class of problems?

解决方案

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>

这篇关于为所有可能的时间序列类创建一个函数方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆