【问题标题】:Enforce equal amount of days each quarter R 'xts'每个季度执行相等的天数 R 'xts'
【发布时间】:2021-08-18 07:53:57
【问题描述】:

假设我有以下数据集:

标准普尔 500 指数的每日观察,以及 季度公共债务总额。 季度的观察是在时间

xxxx-01-01
xxxx-04-01
xxxx-07-01
xxxx-10-01

周末、节假日等非交易日用NA表示

2020-01-01 NA
2020-01-02 3257.85
2020-01-02 3234.85
.
.
.
.
2020-03-31 2584.59

这将导致每季度的观察量不相等。 我的问题是如何删除一定数量的日期,以便在每个季度内我将有 66 个 S&P500 观察值?

【问题讨论】:

    标签: r dataframe time-series xts midasr


    【解决方案1】:

    我们可以将索引转换为yearqtr(来自zoo),用它为前66个观察创建逻辑索引

    xt1[ave(seq_along(index(xt1)), as.yearqtr(index(xt1)), FUN = 
            seq_along) <= 66]
    

    正如 @G.Grothendieck 在 cmets 中提到的那样,我们的想法是首先删除 NA 元素

    xt2 <- na.omit(xt1)
    

    然后,计算每个季度的minimum 元素数

    n <- min(tapply(seq_along(index(xt1)), as.yearqtr(index(xt1)), FUN = length))
    

    在第一个代码块中使用它

    xt2[ave(seq_along(index(xt2)), as.yearqtr(index(xt2)), FUN = 
            seq_along) <= n]
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    • 2015-05-05
    相关资源
    最近更新 更多