【问题标题】:Count observations using rollapply from zoo package with dynamic criteria使用具有动态标准的 zoo 包中的 rollapply 计数观察值
【发布时间】:2018-03-18 01:04:17
【问题描述】:

我正在寻找一种方法来计算像 here 这样的观察结果,但能够根据特定观察结果更改标准(移动计数)。

例如 - 计算大于特定观测值的 mag 观测值(从最后 50 次开始)。 我的代码:

rollapplyr(zoo(mag),50,function(i){sum(mag>i)},partial=T,by.column=F,fill=NA))

此代码采用最后 50 次观测的平均 mag 并计算高于该平均值的观测数(在整个数据集中)。

我错过了什么? 也许在这里使用 rollapply 不是这种情况? 总结一下:
1.根据具体的行值计数
2. 只计算最后 50 个观察值(而不是整个数据列)。

【问题讨论】:

  • 第一个问题是您的函数中的i 是“窗口化”数据和mag,正如您所说,在整个列中。所以代码肯定不是你上面说的。另外,没有示例数据和预期输出,如果可以,请添加。

标签: r zoo rollapply


【解决方案1】:

请看下面的“更正”功能:

set.seed(2017)
mag <- sample(x = 1000, size = 20)

## Your function, see what is printed
# my_fun <- function(i) {
#   print(i)
#   print(mag)
#   sum(mag > i)
# }

## Corrected one
my_fun <- function(i) {
  print(i)
  print(tail(i, 1))
  sum(i > tail(i, 1))
}

# debug(my_fun)  # Play a little with debug(), it is worth it!

mag_out <- zoo::rollapplyr(
  # zoo::zoo(mag),
  mag,
  5,
  my_fun,
  partial = TRUE,
  by.column = FALSE,
  fill = NA
)

rbind(
  mag,
  mag_out
)

输出:

        [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16] [,17] [,18] [,19] [,20]
mag      244  329  987  833  524  112  869  327  488   691    89   224   206    73   803   868   288   365   666   145
mag_out    0    0    0    1    2    4    1    3    2     1     4     3     3     4     0     0     2     2     2     4

【讨论】:

  • 非常感谢 m-dz !我对 R 没有太多经验 - 我会根据您的建议尝试学习如何调试。
猜你喜欢
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 2022-12-06
  • 1970-01-01
  • 2014-05-02
  • 1970-01-01
  • 2013-10-12
  • 1970-01-01
相关资源
最近更新 更多