【问题标题】:Get highest value of X rows获取 X 行的最高值
【发布时间】:2017-07-06 07:02:58
【问题描述】:

我正在寻找一个函数来计算 XTS 对象上前 X 个周期的最大值。该函数将返回具有此类值的向量。

我相信有多种计算方法。令人惊讶的是,我在之前的 SO 问题中找不到这一点。我希望有一个已经为此定义了功能的包。如果没有,也许有人知道如何解决它。

下面的示例显示了 XTS 对象 XTS1 中具有最近 3 个周期的最高值的向量的样子。

library('xts')
XTS1 <- structure(c(12, 7, 7, 22, 24, 30, 26, 23, 27, 30), .indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "", tclass = c("POSIXct", "POSIXt"), tzone = "", class = c("xts", "zoo"), .CLASS = structure("double", class = "CLASS"), formattable = structure(list(formatter = "formatC", format = structure(list(format = "f", digits = 2), .Names = c("format", "digits")), preproc = "percent_preproc", postproc = "percent_postproc"), .Names = c("formatter", "format", "preproc", "postproc")), index = structure(c(1413981900, 1413982800, 1413983700, 1413984600, 1413985500, 1413986400, 1413987300, 1413988200, 1413989100, 1413990000), tzone = "", tclass = c("POSIXct", "POSIXt")), .Dim = c(10L, 1L))

#DESIRED OUTPUT      
                     [,1]   GetHighest(3)
2014-10-22 08:45:00   12              NA
2014-10-22 09:00:00    7              12
2014-10-22 09:15:00    7              12
2014-10-22 09:30:00   22              12
2014-10-22 09:45:00   24              22
2014-10-22 10:00:00   30              24
2014-10-22 10:15:00   26              30
2014-10-22 10:30:00   23              30
2014-10-22 10:45:00   27              30
2014-10-22 11:00:00   30              27

【问题讨论】:

    标签: r function conditional-statements xts


    【解决方案1】:

    你可以使用rollapplyfrom zoo

    所以它看起来像这样:

    GetHighest_3 = rollapply(data = XTS1, width = 3, FUN = max)
    

    然后组合起来:

    cbind(XTS1, GetHighest_3)
    

    我看到的唯一问题是它可能会为前 2 个值返回 NA,而不仅仅是第一个值,因为它的宽度为 3。

    我无法测试代码,因为我现在无法访问 R,所以可能有一些拼写错误。

    【讨论】:

    • 非常感谢。这样可行。 NA 不是问题。我将它滞后 1 并得到我正在寻找的东西。壮观。
    猜你喜欢
    • 1970-01-01
    • 2014-04-22
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    相关资源
    最近更新 更多